b9d2468e1f6b40c8256eb20c57566c152dc9fcb6
[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/cel.h"
74 #include "asterisk/test.h"
75 #include "asterisk/bridging.h"
76 #include "asterisk/bridging_basic.h"
77 #include "asterisk/features_config.h"
78
79 /* BUGBUG TEST_FRAMEWORK is disabled because parking tests no longer work. */
80 #undef TEST_FRAMEWORK
81
82 /*
83  * Party A - transferee
84  * Party B - transferer
85  * Party C - target of transfer
86  *
87  * DTMF attended transfer works within the channel bridge.
88  * Unfortunately, when either party A or B in the channel bridge
89  * hangs up, that channel is not completely hung up until the
90  * transfer completes.  This is a real problem depending upon
91  * the channel technology involved.
92  *
93  * For chan_dahdi, the channel is crippled until the hangup is
94  * complete.  Either the channel is not useable (analog) or the
95  * protocol disconnect messages are held up (PRI/BRI/SS7) and
96  * the media is not released.
97  *
98  * For chan_sip, a call limit of one is going to block that
99  * endpoint from any further calls until the hangup is complete.
100  *
101  * For party A this is a minor problem.  The party A channel
102  * will only be in this condition while party B is dialing and
103  * when party B and C are conferring.  The conversation between
104  * party B and C is expected to be a short one.  Party B is
105  * either asking a question of party C or announcing party A.
106  * Also party A does not have much incentive to hangup at this
107  * point.
108  *
109  * For party B this can be a major problem during a blonde
110  * transfer.  (A blonde transfer is our term for an attended
111  * transfer that is converted into a blind transfer. :))  Party
112  * B could be the operator.  When party B hangs up, he assumes
113  * that he is out of the original call entirely.  The party B
114  * channel will be in this condition while party C is ringing,
115  * while attempting to recall party B, and while waiting between
116  * call attempts.
117  *
118  * WARNING:
119  * The ATXFER_NULL_TECH conditional is a hack to fix the
120  * problem.  It will replace the party B channel technology with
121  * a NULL channel driver.  The consequences of this code is that
122  * the 'h' extension will not be able to access any channel
123  * technology specific information like SIP statistics for the
124  * call.
125  *
126  * Uncomment the ATXFER_NULL_TECH define below to replace the
127  * party B channel technology in the channel bridge to complete
128  * hanging up the channel technology.
129  */
130 //#define ATXFER_NULL_TECH      1
131
132 /*** DOCUMENTATION
133         <application name="Bridge" language="en_US">
134                 <synopsis>
135                         Bridge two channels.
136                 </synopsis>
137                 <syntax>
138                         <parameter name="channel" required="true">
139                                 <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
140                         </parameter>
141                         <parameter name="options">
142                                 <optionlist>
143                                         <option name="p">
144                                                 <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
145                                         </option>
146                                         <option name="F" argsep="^">
147                                                 <argument name="context" required="false" />
148                                                 <argument name="exten" required="false" />
149                                                 <argument name="priority" required="true" />
150                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
151                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
152                                                 <note>
153                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
154                                                         prefixed with one or two underbars ('_').</para>
155                                                 </note>
156                                                 <note>
157                                                         <para>This option will override the 'x' option</para>
158                                                 </note>
159                                         </option>
160                                         <option name="F">
161                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
162                                                 to the next priority of the current extension and <emphasis>start</emphasis> execution
163                                                 at that location.</para>
164                                                 <note>
165                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
166                                                         prefixed with one or two underbars ('_').</para>
167                                                 </note>
168                                                 <note>
169                                                         <para>Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
170                                                 </note>
171                                                 <note>
172                                                         <para>This option will override the 'x' option</para>
173                                                 </note>
174                                         </option>
175
176                                         <option name="h">
177                                                 <para>Allow the called party to hang up by sending the
178                                                 <replaceable>*</replaceable> DTMF digit.</para>
179                                         </option>
180                                         <option name="H">
181                                                 <para>Allow the calling party to hang up by pressing the
182                                                 <replaceable>*</replaceable> DTMF digit.</para>
183                                         </option>
184                                         <option name="k">
185                                                 <para>Allow the called party to enable parking of the call by sending
186                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
187                                         </option>
188                                         <option name="K">
189                                                 <para>Allow the calling party to enable parking of the call by sending
190                                                  the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
191                                         </option>
192                                         <option name="L(x[:y][:z])">
193                                                 <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
194                                                 when <replaceable>y</replaceable> ms are left. Repeat the warning every
195                                                 <replaceable>z</replaceable> ms. The following special variables can be
196                                                 used with this option:</para>
197                                                 <variablelist>
198                                                         <variable name="LIMIT_PLAYAUDIO_CALLER">
199                                                                 <para>Play sounds to the caller. yes|no (default yes)</para>
200                                                         </variable>
201                                                         <variable name="LIMIT_PLAYAUDIO_CALLEE">
202                                                                 <para>Play sounds to the callee. yes|no</para>
203                                                         </variable>
204                                                         <variable name="LIMIT_TIMEOUT_FILE">
205                                                                 <para>File to play when time is up.</para>
206                                                         </variable>
207                                                         <variable name="LIMIT_CONNECT_FILE">
208                                                                 <para>File to play when call begins.</para>
209                                                         </variable>
210                                                         <variable name="LIMIT_WARNING_FILE">
211                                                                 <para>File to play as warning if <replaceable>y</replaceable> is
212                                                                 defined. The default is to say the time remaining.</para>
213                                                         </variable>
214                                                 </variablelist>
215                                         </option>
216                                         <option name="S(x)">
217                                                 <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
218                                         </option>
219                                         <option name="t">
220                                                 <para>Allow the called party to transfer the calling party by sending the
221                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
222                                         </option>
223                                         <option name="T">
224                                                 <para>Allow the calling party to transfer the called party by sending the
225                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
226                                         </option>
227                                         <option name="w">
228                                                 <para>Allow the called party to enable recording of the call by sending
229                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
230                                         </option>
231                                         <option name="W">
232                                                 <para>Allow the calling party to enable recording of the call by sending
233                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
234                                         </option>
235                                         <option name="x">
236                                                 <para>Cause the called party to be hung up after the bridge, instead of being
237                                                 restarted in the dialplan.</para>
238                                         </option>
239                                 </optionlist>
240                         </parameter>
241                 </syntax>
242                 <description>
243                         <para>Allows the ability to bridge two channels via the dialplan.</para>
244                         <para>This application sets the following channel variable upon completion:</para>
245                         <variablelist>
246                                 <variable name="BRIDGERESULT">
247                                         <para>The result of the bridge attempt as a text string.</para>
248                                         <value name="SUCCESS" />
249                                         <value name="FAILURE" />
250                                         <value name="LOOP" />
251                                         <value name="NONEXISTENT" />
252                                         <value name="INCOMPATIBLE" />
253                                 </variable>
254                         </variablelist>
255                 </description>
256         </application>
257         <manager name="Bridge" language="en_US">
258                 <synopsis>
259                         Bridge two channels already in the PBX.
260                 </synopsis>
261                 <syntax>
262                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
263                         <parameter name="Channel1" required="true">
264                                 <para>Channel to Bridge to Channel2.</para>
265                         </parameter>
266                         <parameter name="Channel2" required="true">
267                                 <para>Channel to Bridge to Channel1.</para>
268                         </parameter>
269                         <parameter name="Tone">
270                                 <para>Play courtesy tone to Channel 2.</para>
271                                 <enumlist>
272                                         <enum name="no" />
273                                         <enum name="Channel1" />
274                                         <enum name="Channel2" />
275                                         <enum name="Both" />
276                                 </enumlist>
277                         </parameter>
278                 </syntax>
279                 <description>
280                         <para>Bridge together two channels already in the PBX.</para>
281                 </description>
282         </manager>
283         <managerEvent language="en_US" name="ParkedCallTimeOut">
284                 <managerEventInstance class="EVENT_FLAG_CALL">
285                         <synopsis>Raised when a parked call times out.</synopsis>
286                         <syntax>
287                                 <parameter name="Exten">
288                                         <para>The parking lot extension.</para>
289                                 </parameter>
290                                 <parameter name="Channel"/>
291                                 <parameter name="Parkinglot">
292                                         <para>The name of the parking lot.</para>
293                                 </parameter>
294                                 <parameter name="CallerIDNum"/>
295                                 <parameter name="CallerIDName"/>
296                                 <parameter name="ConnectedLineNum"/>
297                                 <parameter name="ConnectedLineName"/>
298                                 <parameter name="UniqueID"/>
299                         </syntax>
300                         <see-also>
301                                 <ref type="managerEvent">ParkedCall</ref>
302                         </see-also>
303                 </managerEventInstance>
304         </managerEvent>
305         <managerEvent language="en_US" name="ParkedCallGiveUp">
306                 <managerEventInstance class="EVENT_FLAG_CALL">
307                         <synopsis>Raised when a parked call hangs up while in the parking lot.</synopsis>
308                         <syntax>
309                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='ParkedCallTimeOut']/managerEventInstance/syntax/parameter[@name='Exten'])" />
310                                 <parameter name="Channel"/>
311                                 <xi:include xpointer="xpointer(/docs/managerEvent[@name='ParkedCallTimeOut']/managerEventInstance/syntax/parameter[@name='Parkinglot'])" />
312                                 <parameter name="CallerIDNum"/>
313                                 <parameter name="CallerIDName"/>
314                                 <parameter name="ConnectedLineNum"/>
315                                 <parameter name="ConnectedLineName"/>
316                                 <parameter name="UniqueID"/>
317                         </syntax>
318                         <see-also>
319                                 <ref type="managerEvent">ParkedCall</ref>
320                         </see-also>
321                 </managerEventInstance>
322         </managerEvent>
323  ***/
324
325 #define DEFAULT_PARK_TIME                                                       45000   /*!< ms */
326 #define DEFAULT_PARK_EXTENSION                                          "700"
327 #define DEFAULT_COMEBACK_CONTEXT                                        "parkedcallstimeout"
328 #define DEFAULT_COMEBACK_TO_ORIGIN                                      1
329 #define DEFAULT_COMEBACK_DIAL_TIME                                      30
330
331 #define AST_MAX_WATCHERS 256
332 #define MAX_DIAL_FEATURE_OPTIONS 30
333
334 /* TODO Scrape all of the parking stuff out of features.c */
335
336 typedef enum {
337         FEATURE_INTERPRET_DETECT, /* Used by ast_feature_detect */
338         FEATURE_INTERPRET_DO,     /* Used by feature_interpret */
339         FEATURE_INTERPRET_CHECK,  /* Used by feature_check */
340 } feature_interpret_op;
341
342 /*! Parking lot access ramp dialplan usage entry. */
343 struct parking_dp_ramp {
344         /*! Next node in the parking lot spaces dialplan list. */
345         AST_LIST_ENTRY(parking_dp_ramp) node;
346         /*! TRUE if the parking lot access extension is exclusive. */
347         unsigned int exclusive:1;
348         /*! Parking lot access extension */
349         char exten[1];
350 };
351
352 /*! Parking lot dialplan access ramp map */
353 AST_LIST_HEAD_NOLOCK(parking_dp_ramp_map, parking_dp_ramp);
354
355 /*! Parking lot spaces dialplan usage entry. */
356 struct parking_dp_spaces {
357         /*! Next node in the parking lot spaces dialplan list. */
358         AST_LIST_ENTRY(parking_dp_spaces) node;
359         /*! First parking space */
360         int start;
361         /*! Last parking space */
362         int stop;
363 };
364
365 /*! Parking lot dialplan context space map */
366 AST_LIST_HEAD_NOLOCK(parking_dp_space_map, parking_dp_spaces);
367
368 /*! Parking lot context dialplan usage entry. */
369 struct parking_dp_context {
370         /*! Next node in the parking lot contexts dialplan list. */
371         AST_LIST_ENTRY(parking_dp_context) node;
372         /*! Parking access extensions defined in this context. */
373         struct parking_dp_ramp_map access_extens;
374         /*! Parking spaces defined in this context. */
375         struct parking_dp_space_map spaces;
376         /*! Parking hints defined in this context. */
377         struct parking_dp_space_map hints;
378         /*! Parking lot context name */
379         char context[1];
380 };
381
382 /*! Parking lot dialplan usage map. */
383 AST_LIST_HEAD_NOLOCK(parking_dp_map, parking_dp_context);
384
385 /*!
386  * \brief Description of one parked call, added to a list while active, then removed.
387  * The list belongs to a parkinglot.
388  */
389 struct parkeduser {
390         struct ast_channel *chan;                   /*!< Parked channel */
391         struct timeval start;                       /*!< Time the park started */
392         int parkingnum;                             /*!< Parking lot space used */
393         char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
394         char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
395         char exten[AST_MAX_EXTENSION];
396         int priority;
397         unsigned int parkingtime;                   /*!< Maximum length in parking lot before return */
398         /*! Method to entertain the caller when parked: AST_CONTROL_RINGING, AST_CONTROL_HOLD, or 0(none) */
399         enum ast_control_frame_type hold_method;
400         unsigned int notquiteyet:1;
401         unsigned int options_specified:1;
402         char peername[AST_CHANNEL_NAME];
403         unsigned char moh_trys;
404         /*! Parking lot this entry belongs to.  Holds a parking lot reference. */
405         struct ast_parkinglot *parkinglot;
406         AST_LIST_ENTRY(parkeduser) list;
407 };
408
409 /*! Parking lot configuration options. */
410 struct parkinglot_cfg {
411         /*! Music class used for parking */
412         char mohclass[MAX_MUSICCLASS];
413         /*! Extension to park calls in this parking lot. */
414         char parkext[AST_MAX_EXTENSION];
415         /*! Context for which parking is made accessible */
416         char parking_con[AST_MAX_CONTEXT];
417         /*! Context that timed-out parked calls are called back on when comebacktoorigin=no */
418         char comebackcontext[AST_MAX_CONTEXT];
419         /*! First available extension for parking */
420         int parking_start;
421         /*! Last available extension for parking */
422         int parking_stop;
423         /*! Default parking time in ms. */
424         unsigned int parkingtime;
425         /*!
426          * \brief Enable DTMF based transfers on bridge when picking up parked calls.
427          *
428          * \details
429          * none(0)
430          * AST_FEATURE_FLAG_BYCALLEE
431          * AST_FEATURE_FLAG_BYCALLER
432          * AST_FEATURE_FLAG_BYBOTH
433          */
434         int parkedcalltransfers;
435         /*!
436          * \brief Enable DTMF based parking on bridge when picking up parked calls.
437          *
438          * \details
439          * none(0)
440          * AST_FEATURE_FLAG_BYCALLEE
441          * AST_FEATURE_FLAG_BYCALLER
442          * AST_FEATURE_FLAG_BYBOTH
443          */
444         int parkedcallreparking;
445         /*!
446          * \brief Enable DTMF based hangup on a bridge when pickup up parked calls.
447          *
448          * \details
449          * none(0)
450          * AST_FEATURE_FLAG_BYCALLEE
451          * AST_FEATURE_FLAG_BYCALLER
452          * AST_FEATURE_FLAG_BYBOTH
453          */
454         int parkedcallhangup;
455         /*!
456          * \brief Enable DTMF based recording on a bridge when picking up parked calls.
457          *
458          * \details
459          * none(0)
460          * AST_FEATURE_FLAG_BYCALLEE
461          * AST_FEATURE_FLAG_BYCALLER
462          * AST_FEATURE_FLAG_BYBOTH
463          */
464         int parkedcallrecording;
465
466         /*! Time in seconds to dial the device that parked a timedout parked call */
467         unsigned int comebackdialtime;
468         /*! TRUE if findslot is set to next */
469         unsigned int parkfindnext:1;
470         /*! TRUE if the parking lot is exclusively accessed by parkext */
471         unsigned int parkext_exclusive:1;
472         /*! Add parking hints automatically */
473         unsigned int parkaddhints:1;
474         /*! TRUE if configuration is invalid and the parking lot should not be used. */
475         unsigned int is_invalid:1;
476         /*! TRUE if a timed out parked call goes back to the parker */
477         unsigned int comebacktoorigin:1;
478 };
479
480 /*! \brief Structure for parking lots which are put in a container. */
481 struct ast_parkinglot {
482         /*! Name of the parking lot. */
483         char name[AST_MAX_CONTEXT];
484         /*! Parking lot user configuration. */
485         struct parkinglot_cfg cfg;
486
487         /*! Parking space to start next park search. */
488         int next_parking_space;
489
490         /*! That which bears the_mark shall be deleted if parking lot empty! (Used during reloads.) */
491         unsigned int the_mark:1;
492         /*! TRUE if the parking lot is disabled. */
493         unsigned int disabled:1;
494
495         /*! List of active parkings in this parkinglot */
496         AST_LIST_HEAD(parkinglot_parklist, parkeduser) parkings;
497 };
498
499 /*! \brief The configured parking lots container. Always at least one  - the default parking lot */
500 static struct ao2_container *parkinglots;
501
502 /*!
503  * \brief Default parking lot.
504  * \note Holds a parkinglot reference.
505  * \note Will not be NULL while running.
506  */
507 static struct ast_parkinglot *default_parkinglot;
508
509 /*! Force a config reload to reload regardless of config file timestamp. */
510 #ifdef TEST_FRAMEWORK
511 static int force_reload_load;
512 #endif
513
514 static int parkeddynamic = 0;                              /*!< Enable creation of parkinglots dynamically */
515
516 /*!
517  * \brief Context for parking dialback to parker.
518  * \note The need for the context is a KLUDGE.
519  *
520  * \todo Might be able to eliminate the parking_con_dial context
521  * kludge by running app_dial directly in its own thread to
522  * simulate a PBX.
523  */
524 static char parking_con_dial[] = "park-dial";
525
526 /*! Ensure that features.conf reloads on one thread at a time. */
527 AST_MUTEX_DEFINE_STATIC(features_reload_lock);
528
529 static int adsipark;
530
531 static char *registrar = "features";               /*!< Registrar for operations */
532
533 /*! PARK_APP_NAME application arguments */
534 AST_DEFINE_APP_ARGS_TYPE(park_app_args,
535         AST_APP_ARG(timeout);           /*!< Time in ms to remain in the parking lot. */
536         AST_APP_ARG(return_con);        /*!< Context to return parked call if timeout. */
537         AST_APP_ARG(return_ext);        /*!< Exten to return parked call if timeout. */
538         AST_APP_ARG(return_pri);        /*!< Priority to return parked call if timeout. */
539         AST_APP_ARG(options);           /*!< Parking option flags. */
540         AST_APP_ARG(pl_name);           /*!< Parking lot name to use if present. */
541         AST_APP_ARG(dummy);                     /*!< Place to put any remaining args string. */
542         );
543
544 /* module and CLI command definitions */
545 static const char *parkcall = "Park";
546
547 static pthread_t parking_thread;
548 struct ast_dial_features {
549         /*! Channel's feature flags. */
550         struct ast_flags my_features;
551         /*! Bridge peer's feature flags. */
552         struct ast_flags peer_features;
553 };
554
555 #if defined(ATXFER_NULL_TECH)
556 /*!
557  * \internal
558  * \brief Set the channel technology to the kill technology.
559  *
560  * \param chan Channel to change technology.
561  *
562  * \return Nothing
563  */
564 static void set_kill_chan_tech(struct ast_channel *chan)
565 {
566         int idx;
567
568         ast_channel_lock(chan);
569
570         /* Hangup the channel's physical side */
571         if (ast_channel_tech(chan)->hangup) {
572                 ast_channel_tech(chan)->hangup(chan);
573         }
574         if (ast_channel_tech_pvt(chan)) {
575                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n",
576                         ast_channel_name(chan));
577                 ast_free(ast_channel_tech_pvt(chan));
578                 ast_channel_tech_pvt_set(chan, NULL);
579         }
580
581         /* Install the kill technology and wake up anyone waiting on it. */
582         ast_channel_tech_set(chan, &ast_kill_tech);
583         for (idx = 0; idx < AST_MAX_FDS; ++idx) {
584                 switch (idx) {
585                 case AST_ALERT_FD:
586                 case AST_TIMING_FD:
587                 case AST_GENERATOR_FD:
588                         /* Don't clear these fd's. */
589                         break;
590                 default:
591                         ast_channel_set_fd(chan, idx, -1);
592                         break;
593                 }
594         }
595         ast_queue_frame(chan, &ast_null_frame);
596
597         ast_channel_unlock(chan);
598 }
599 #endif  /* defined(ATXFER_NULL_TECH) */
600
601 #if defined(ATXFER_NULL_TECH)
602 /*!
603  * \internal
604  * \brief Set the channel name to something unique.
605  *
606  * \param chan Channel to change name.
607  *
608  * \return Nothing
609  */
610 static void set_new_chan_name(struct ast_channel *chan)
611 {
612         static int seq_num_last;
613         int seq_num;
614         int len;
615         char *chan_name;
616         char dummy[1];
617
618         /* Create the new channel name string. */
619         ast_channel_lock(chan);
620         seq_num = ast_atomic_fetchadd_int(&seq_num_last, +1);
621         len = snprintf(dummy, sizeof(dummy), "%s<XFER_%x>", ast_channel_name(chan), seq_num) + 1;
622         chan_name = ast_alloca(len);
623         snprintf(chan_name, len, "%s<XFER_%x>", ast_channel_name(chan), seq_num);
624         ast_channel_unlock(chan);
625
626         ast_change_name(chan, chan_name);
627 }
628 #endif  /* defined(ATXFER_NULL_TECH) */
629
630 static void *dial_features_duplicate(void *data)
631 {
632         struct ast_dial_features *df = data, *df_copy;
633
634         if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
635                 return NULL;
636         }
637
638         memcpy(df_copy, df, sizeof(*df));
639
640         return df_copy;
641 }
642
643 static const struct ast_datastore_info dial_features_info = {
644         .type = "dial-features",
645         .destroy = ast_free_ptr,
646         .duplicate = dial_features_duplicate,
647 };
648
649 /*!
650  * \internal
651  * \brief Set the features datastore if it doesn't exist.
652  *
653  * \param chan Channel to add features datastore
654  * \param my_features The channel's feature flags
655  * \param peer_features The channel's bridge peer feature flags
656  *
657  * \retval TRUE if features datastore already existed.
658  */
659 static int add_features_datastore(struct ast_channel *chan, const struct ast_flags *my_features, const struct ast_flags *peer_features)
660 {
661         struct ast_datastore *datastore;
662         struct ast_dial_features *dialfeatures;
663
664         ast_channel_lock(chan);
665         datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL);
666         ast_channel_unlock(chan);
667         if (datastore) {
668                 /* Already exists. */
669                 return 1;
670         }
671
672         /* Create a new datastore with specified feature flags. */
673         datastore = ast_datastore_alloc(&dial_features_info, NULL);
674         if (!datastore) {
675                 ast_log(LOG_WARNING, "Unable to create channel features datastore.\n");
676                 return 0;
677         }
678         dialfeatures = ast_calloc(1, sizeof(*dialfeatures));
679         if (!dialfeatures) {
680                 ast_log(LOG_WARNING, "Unable to allocate memory for feature flags.\n");
681                 ast_datastore_free(datastore);
682                 return 0;
683         }
684         ast_copy_flags(&dialfeatures->my_features, my_features, AST_FLAGS_ALL);
685         ast_copy_flags(&dialfeatures->peer_features, peer_features, AST_FLAGS_ALL);
686         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
687         datastore->data = dialfeatures;
688         ast_channel_lock(chan);
689         ast_channel_datastore_add(chan, datastore);
690         ast_channel_unlock(chan);
691         return 0;
692 }
693
694 /* Forward declarations */
695 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
696 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
697 static struct ast_parkinglot *find_parkinglot(const char *name);
698 static struct ast_parkinglot *create_parkinglot(const char *name);
699 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
700 static int parkinglot_activate(struct ast_parkinglot *parkinglot);
701 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile);
702
703 /*!
704  * \internal
705  * \brief Get the parking extension if it exists.
706  *
707  * \param exten_str Parking extension to see if exists.
708  * \param chan Channel to autoservice while looking for exten.  (Could be NULL)
709  * \param context Parking context to look in for exten.
710  *
711  * \retval exten on success.
712  * \retval NULL on error or exten does not exist.
713  */
714 static struct ast_exten *get_parking_exten(const char *exten_str, struct ast_channel *chan, const char *context)
715 {
716         struct ast_exten *exten;
717         struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
718         const char *app_at_exten;
719
720         ast_debug(4, "Checking if %s@%s is a parking exten\n", exten_str, context);
721         exten = pbx_find_extension(chan, NULL, &q, context, exten_str, 1, NULL, NULL,
722                 E_MATCH);
723         if (!exten) {
724                 return NULL;
725         }
726
727         app_at_exten = ast_get_extension_app(exten);
728         if (!app_at_exten || strcasecmp(parkcall, app_at_exten)) {
729                 return NULL;
730         }
731
732         return exten;
733 }
734
735 int ast_parking_ext_valid(const char *exten_str, struct ast_channel *chan, const char *context)
736 {
737         return get_parking_exten(exten_str, chan, context) ? 1 : 0;
738 }
739
740 struct ast_bridge_thread_obj
741 {
742         struct ast_bridge_config bconfig;
743         struct ast_channel *chan;
744         struct ast_channel *peer;
745         struct ast_callid *callid;                             /*<! callid pointer (Only used to bind thread) */
746         unsigned int return_to_pbx:1;
747 };
748
749 static int parkinglot_hash_cb(const void *obj, const int flags)
750 {
751         const struct ast_parkinglot *parkinglot = obj;
752
753         return ast_str_case_hash(parkinglot->name);
754 }
755
756 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
757 {
758         struct ast_parkinglot *parkinglot = obj;
759         struct ast_parkinglot *parkinglot2 = arg;
760
761         return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
762 }
763
764 /*!
765  * \brief store context, extension and priority
766  * \param chan, context, ext, pri
767  */
768 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
769 {
770         ast_channel_context_set(chan, context);
771         ast_channel_exten_set(chan, ext);
772         ast_channel_priority_set(chan, pri);
773 }
774
775 #if 0
776 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
777         const char *caller_name, struct ast_channel *requestor,
778         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, const char *addr,
779         int timeout, int *outstate, const char *language);
780 #endif
781
782 static const struct ast_datastore_info channel_app_data_datastore = {
783         .type = "Channel appdata datastore",
784         .destroy = ast_free_ptr,
785 };
786
787 #if 0
788 static int set_chan_app_data(struct ast_channel *chan, const char *src_app_data)
789 {
790         struct ast_datastore *datastore;
791         char *dst_app_data;
792
793         datastore = ast_datastore_alloc(&channel_app_data_datastore, NULL);
794         if (!datastore) {
795                 return -1;
796         }
797
798         dst_app_data = ast_malloc(strlen(src_app_data) + 1);
799         if (!dst_app_data) {
800                 ast_datastore_free(datastore);
801                 return -1;
802         }
803
804         ast_channel_data_set(chan, strcpy(dst_app_data, src_app_data));
805         datastore->data = dst_app_data;
806         ast_channel_datastore_add(chan, datastore);
807         return 0;
808 }
809 #endif
810
811 #if 0
812 /*!
813  * \brief bridge the call
814  * \param data thread bridge.
815  *
816  * Set Last Data for respective channels, reset cdr for channels
817  * bridge call, check if we're going back to dialplan
818  * if not hangup both legs of the call
819  */
820 static void *bridge_call_thread(void *data)
821 {
822         struct ast_bridge_thread_obj *tobj = data;
823
824         if (tobj->callid) {
825                 ast_callid_threadassoc_add(tobj->callid);
826                 /* Need to deref and set to null since ast_bridge_thread_obj has no common destructor */
827                 tobj->callid = ast_callid_unref(tobj->callid);
828         }
829
830         ast_channel_appl_set(tobj->chan, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
831         if (set_chan_app_data(tobj->chan, ast_channel_name(tobj->peer))) {
832                 ast_channel_data_set(tobj->chan, "(Empty)");
833         }
834         ast_channel_appl_set(tobj->peer, !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge");
835         if (set_chan_app_data(tobj->peer, ast_channel_name(tobj->chan))) {
836                 ast_channel_data_set(tobj->peer, "(Empty)");
837         }
838
839         if (tobj->return_to_pbx) {
840                 ast_after_bridge_set_goto(tobj->chan, ast_channel_context(tobj->chan),
841                         ast_channel_exten(tobj->chan), ast_channel_priority(tobj->chan));
842                 ast_after_bridge_set_goto(tobj->peer, ast_channel_context(tobj->peer),
843                         ast_channel_exten(tobj->peer), ast_channel_priority(tobj->peer));
844         }
845
846         ast_bridge_call(tobj->chan, tobj->peer, &tobj->bconfig);
847
848         ast_after_bridge_goto_run(tobj->chan);
849
850         ast_free(tobj);
851
852         return NULL;
853 }
854 #endif
855
856 #if 0
857 /*!
858  * \brief create thread for the bridging call
859  * \param tobj
860  */
861 static void bridge_call_thread_launch(struct ast_bridge_thread_obj *tobj)
862 {
863         pthread_t thread;
864
865         /* This needs to be unreffed once it has been associated with the new thread. */
866         tobj->callid = ast_read_threadstorage_callid();
867
868         if (ast_pthread_create_detached(&thread, NULL, bridge_call_thread, tobj)) {
869                 ast_log(LOG_ERROR, "Failed to create bridge_call_thread.\n");
870                 ast_callid_unref(tobj->callid);
871                 ast_hangup(tobj->chan);
872                 ast_hangup(tobj->peer);
873                 ast_free(tobj);
874         }
875 }
876 #endif
877
878 /*!
879  * \brief Announce call parking by ADSI
880  * \param chan .
881  * \param parkingexten .
882  * Create message to show for ADSI, display message.
883  * \retval 0 on success.
884  * \retval -1 on failure.
885  */
886 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
887 {
888         int res;
889         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
890         char tmp[256];
891         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
892
893         snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
894         message[0] = tmp;
895         res = ast_adsi_load_session(chan, NULL, 0, 1);
896         if (res == -1)
897                 return res;
898         return ast_adsi_print(chan, message, justify, 1);
899 }
900
901 /*!
902  * \brief Find parking lot name from channel
903  * \note Channel needs to be locked while the returned string is in use.
904  */
905 static const char *findparkinglotname(struct ast_channel *chan)
906 {
907         const char *name;
908
909         /* The channel variable overrides everything */
910         name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
911         if (!name && !ast_strlen_zero(ast_channel_parkinglot(chan))) {
912                 /* Use the channel's parking lot. */
913                 name = ast_channel_parkinglot(chan);
914         }
915         return name;
916 }
917
918 /*! \brief Notify metermaids that we've changed an extension */
919 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
920 {
921         ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'",
922                 exten, context, ast_devstate2str(state));
923
924         ast_devstate_changed(state, AST_DEVSTATE_CACHABLE, "park:%s@%s", exten, context);
925 }
926
927 /*! \brief metermaids callback from devicestate.c */
928 static enum ast_device_state metermaidstate(const char *data)
929 {
930         char *context;
931         char *exten;
932
933         context = ast_strdupa(data);
934
935         exten = strsep(&context, "@");
936         if (!context)
937                 return AST_DEVICE_INVALID;
938
939         ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
940
941         if (!ast_exists_extension(NULL, context, exten, 1, NULL))
942                 return AST_DEVICE_NOT_INUSE;
943
944         return AST_DEVICE_INUSE;
945 }
946
947 /*! Options to pass to park_call_full */
948 enum ast_park_call_options {
949         /*! Provide ringing to the parked caller instead of music on hold */
950         AST_PARK_OPT_RINGING =   (1 << 0),
951         /*! Randomly choose a parking spot for the caller instead of choosing
952          *  the first one that is available. */
953         AST_PARK_OPT_RANDOMIZE = (1 << 1),
954         /*! Do not announce the parking number */
955         AST_PARK_OPT_SILENCE = (1 << 2),
956 };
957
958 /*! Optional additional parking options when parking a call. */
959 struct ast_park_call_args {
960         /*! How long to wait in the parking lot before the call gets sent back
961          *  to the specified return extension (or a best guess at where it came
962          *  from if not explicitly specified). */
963         int timeout;
964         /*! An output parameter to store the parking space where the parked caller
965          *  was placed. */
966         int *extout;
967         const char *orig_chan_name;
968         const char *return_con;
969         const char *return_ext;
970         int return_pri;
971         uint32_t flags;
972         /*! Parked user that has already obtained a parking space */
973         struct parkeduser *pu;
974         /*! \brief Parkinglot to be parked in */
975         struct ast_parkinglot *parkinglot;
976 };
977
978 /*!
979  * \internal
980  * \brief Create a dynamic parking lot.
981  *
982  * \param name Dynamic parking lot name to create.
983  * \param chan Channel to get dynamic parking lot parameters.
984  *
985  * \retval parkinglot on success.
986  * \retval NULL on error.
987  */
988 static struct ast_parkinglot *create_dynamic_parkinglot(const char *name, struct ast_channel *chan)
989 {
990         const char *dyn_context;
991         const char *dyn_exten;
992         const char *dyn_range;
993         const char *template_name;
994         struct ast_parkinglot *template_parkinglot = NULL;
995         struct ast_parkinglot *parkinglot;
996         int dyn_start;
997         int dyn_end;
998
999         ast_channel_lock(chan);
1000         template_name = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
1001         dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
1002         dyn_exten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNEXTEN"), ""));
1003         dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
1004         ast_channel_unlock(chan);
1005
1006         if (!ast_strlen_zero(template_name)) {
1007                 template_parkinglot = find_parkinglot(template_name);
1008                 if (!template_parkinglot) {
1009                         ast_debug(1, "PARKINGDYNAMIC lot %s does not exist.\n",
1010                                 template_name);
1011                 } else if (template_parkinglot->cfg.is_invalid) {
1012                         ast_debug(1, "PARKINGDYNAMIC lot %s has invalid config.\n",
1013                                 template_name);
1014                         parkinglot_unref(template_parkinglot);
1015                         template_parkinglot = NULL;
1016                 }
1017         }
1018         if (!template_parkinglot) {
1019                 template_parkinglot = parkinglot_addref(default_parkinglot);
1020                 ast_debug(1, "Using default parking lot for template\n");
1021         }
1022
1023         parkinglot = copy_parkinglot(name, template_parkinglot);
1024         if (!parkinglot) {
1025                 ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
1026         } else {
1027                 /* Configure the dynamic parking lot. */
1028                 if (!ast_strlen_zero(dyn_context)) {
1029                         ast_copy_string(parkinglot->cfg.parking_con, dyn_context,
1030                                 sizeof(parkinglot->cfg.parking_con));
1031                 }
1032                 if (!ast_strlen_zero(dyn_exten)) {
1033                         ast_copy_string(parkinglot->cfg.parkext, dyn_exten,
1034                                 sizeof(parkinglot->cfg.parkext));
1035                 }
1036                 if (!ast_strlen_zero(dyn_range)) {
1037                         if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
1038                                 ast_log(LOG_WARNING,
1039                                         "Format for parking positions is a-b, where a and b are numbers\n");
1040                         } else if (dyn_end < dyn_start || dyn_start <= 0 || dyn_end <= 0) {
1041                                 ast_log(LOG_WARNING,
1042                                         "Format for parking positions is a-b, where a <= b\n");
1043                         } else {
1044                                 parkinglot->cfg.parking_start = dyn_start;
1045                                 parkinglot->cfg.parking_stop = dyn_end;
1046                         }
1047                 }
1048
1049                 /*
1050                  * Sanity check for dynamic parking lot configuration.
1051                  *
1052                  * XXX It may be desirable to instead check if the dynamic
1053                  * parking lot overlaps any existing lots like what is done for
1054                  * a reload.
1055                  */
1056                 if (!strcmp(parkinglot->cfg.parking_con, template_parkinglot->cfg.parking_con)) {
1057                         if (!strcmp(parkinglot->cfg.parkext, template_parkinglot->cfg.parkext)
1058                                 && parkinglot->cfg.parkext_exclusive) {
1059                                 ast_log(LOG_WARNING,
1060                                         "Parking lot '%s' conflicts with template parking lot '%s'!\n"
1061                                         "Change either PARKINGDYNCONTEXT or PARKINGDYNEXTEN.\n",
1062                                         parkinglot->name, template_parkinglot->name);
1063                         }
1064                         if ((template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_start
1065                                         && parkinglot->cfg.parking_start <= template_parkinglot->cfg.parking_stop)
1066                                 || (template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_stop
1067                                         && parkinglot->cfg.parking_stop <= template_parkinglot->cfg.parking_stop)
1068                                 || (parkinglot->cfg.parking_start < template_parkinglot->cfg.parking_start
1069                                         && template_parkinglot->cfg.parking_stop < parkinglot->cfg.parking_stop)) {
1070                                 ast_log(LOG_WARNING,
1071                                         "Parking lot '%s' parking spaces overlap template parking lot '%s'!\n"
1072                                         "Change PARKINGDYNPOS.\n",
1073                                         parkinglot->name, template_parkinglot->name);
1074                         }
1075                 }
1076
1077                 parkinglot_activate(parkinglot);
1078                 ao2_link(parkinglots, parkinglot);
1079         }
1080         parkinglot_unref(template_parkinglot);
1081
1082         return parkinglot;
1083 }
1084
1085 /*!
1086  * \internal
1087  * \brief Abort parking a call that has not completed parking yet.
1088  *
1089  * \param pu Parked user item to clean up.
1090  *
1091  * \note The parking lot parkings list is locked on entry.
1092  *
1093  * \return Nothing
1094  */
1095 static void park_space_abort(struct parkeduser *pu)
1096 {
1097         struct ast_parkinglot *parkinglot;
1098
1099         parkinglot = pu->parkinglot;
1100
1101         /* Put back the parking space just allocated. */
1102         --parkinglot->next_parking_space;
1103
1104         AST_LIST_REMOVE(&parkinglot->parkings, pu, list);
1105
1106         AST_LIST_UNLOCK(&parkinglot->parkings);
1107         parkinglot_unref(parkinglot);
1108         ast_free(pu);
1109 }
1110
1111 /*!
1112  * \internal
1113  * \brief Reserve a parking space in a parking lot for a call being parked.
1114  *
1115  * \param park_me Channel being parked.
1116  * \param parker Channel parking the call.
1117  * \param args Optional additional parking options when parking a call.
1118  *
1119  * \return Parked call descriptor or NULL if failed.
1120  * \note The parking lot list is locked if successful.
1121  */
1122 static struct parkeduser *park_space_reserve(struct ast_channel *park_me, struct ast_channel *parker, struct ast_park_call_args *args)
1123 {
1124         struct parkeduser *pu;
1125         int i;
1126         int parking_space = -1;
1127         const char *parkinglotname;
1128         const char *parkingexten;
1129         struct parkeduser *cur;
1130         struct ast_parkinglot *parkinglot = NULL;
1131
1132         if (args->parkinglot) {
1133                 parkinglot = parkinglot_addref(args->parkinglot);
1134                 parkinglotname = parkinglot->name;
1135         } else {
1136                 if (parker) {
1137                         parkinglotname = findparkinglotname(parker);
1138                 } else { /* parker was NULL, check park_me (ParkAndAnnounce / res_agi) */
1139                         parkinglotname = findparkinglotname(park_me);
1140                 }
1141                 if (!ast_strlen_zero(parkinglotname)) {
1142                         parkinglot = find_parkinglot(parkinglotname);
1143                 } else {
1144                         /* Parking lot is not specified, so use the default parking lot. */
1145                         ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
1146                         parkinglot = parkinglot_addref(default_parkinglot);
1147                 }
1148         }
1149
1150         /* Dynamically create parkinglot */
1151         if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
1152                 parkinglot = create_dynamic_parkinglot(parkinglotname, park_me);
1153         }
1154
1155         if (!parkinglot) {
1156                 ast_log(LOG_WARNING, "Parking lot not available to park %s.\n", ast_channel_name(park_me));
1157                 return NULL;
1158         }
1159
1160         ast_debug(1, "Parking lot: %s\n", parkinglot->name);
1161         if (parkinglot->disabled || parkinglot->cfg.is_invalid) {
1162                 ast_log(LOG_WARNING, "Parking lot %s is not in a useable state.\n",
1163                         parkinglot->name);
1164                 parkinglot_unref(parkinglot);
1165                 return NULL;
1166         }
1167
1168         /* Allocate memory for parking data */
1169         if (!(pu = ast_calloc(1, sizeof(*pu)))) {
1170                 parkinglot_unref(parkinglot);
1171                 return NULL;
1172         }
1173
1174         /* Lock parking list */
1175         AST_LIST_LOCK(&parkinglot->parkings);
1176
1177         /* Check for channel variable PARKINGEXTEN */
1178         parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(park_me, "PARKINGEXTEN"), ""));
1179         if (!ast_strlen_zero(parkingexten)) {
1180                 /*!
1181                  * \note The API forces us to specify a numeric parking slot, even
1182                  * though the architecture would tend to support non-numeric extensions
1183                  * (as are possible with SIP, for example).  Hence, we enforce that
1184                  * limitation here.  If extout was not numeric, we could permit
1185                  * arbitrary non-numeric extensions.
1186                  */
1187                 if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space <= 0) {
1188                         ast_log(LOG_WARNING, "PARKINGEXTEN='%s' is not a valid parking space.\n",
1189                                 parkingexten);
1190                         AST_LIST_UNLOCK(&parkinglot->parkings);
1191                         parkinglot_unref(parkinglot);
1192                         ast_free(pu);
1193                         return NULL;
1194                 }
1195
1196                 if (parking_space < parkinglot->cfg.parking_start
1197                         || parkinglot->cfg.parking_stop < parking_space) {
1198                         /*
1199                          * Cannot allow park because parking lots are not setup for
1200                          * spaces outside of the lot.  (Things like dialplan hints don't
1201                          * exist for outside lot space.)
1202                          */
1203                         ast_log(LOG_WARNING, "PARKINGEXTEN=%d is not in %s (%d-%d).\n",
1204                                 parking_space, parkinglot->name, parkinglot->cfg.parking_start,
1205                                 parkinglot->cfg.parking_stop);
1206                         AST_LIST_UNLOCK(&parkinglot->parkings);
1207                         parkinglot_unref(parkinglot);
1208                         ast_free(pu);
1209                         return NULL;
1210                 }
1211
1212                 /* Check if requested parking space is in use. */
1213                 AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1214                         if (cur->parkingnum == parking_space) {
1215                                 ast_log(LOG_WARNING, "PARKINGEXTEN=%d is already in use in %s\n",
1216                                         parking_space, parkinglot->name);
1217                                 AST_LIST_UNLOCK(&parkinglot->parkings);
1218                                 parkinglot_unref(parkinglot);
1219                                 ast_free(pu);
1220                                 return NULL;
1221                         }
1222                 }
1223         } else {
1224                 /* PARKINGEXTEN is empty, so find a usable extension in the lot to park the call */
1225                 int start; /* The first slot we look in the parkinglot. It can be randomized. */
1226                 int start_checked = 0; /* flag raised once the first slot is checked */
1227
1228                 /* If using randomize mode, set start to random position on parking range */
1229                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
1230                         start = ast_random() % (parkinglot->cfg.parking_stop - parkinglot->cfg.parking_start + 1);
1231                         start += parkinglot->cfg.parking_start;
1232                 } else if (parkinglot->cfg.parkfindnext
1233                         && parkinglot->cfg.parking_start <= parkinglot->next_parking_space
1234                         && parkinglot->next_parking_space <= parkinglot->cfg.parking_stop) {
1235                         /* Start looking with the next parking space in the lot. */
1236                         start = parkinglot->next_parking_space;
1237                 } else {
1238                         /* Otherwise, just set it to the start position. */
1239                         start = parkinglot->cfg.parking_start;
1240                 }
1241
1242                 /* free parking extension linear search: O(n^2) */
1243                 for (i = start; ; i++) {
1244                         /* If we are past the end, wrap around to the first parking slot*/
1245                         if (i == parkinglot->cfg.parking_stop + 1) {
1246                                 i = parkinglot->cfg.parking_start;
1247                         }
1248
1249                         if (i == start) {
1250                                 /* At this point, if start_checked, we've exhausted all the possible slots. */
1251                                 if (start_checked) {
1252                                         break;
1253                                 } else {
1254                                         start_checked = 1;
1255                                 }
1256                         }
1257
1258                         /* Search the list of parked calls already in use for i. If we find it, it's in use. */
1259                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1260                                 if (cur->parkingnum == i) {
1261                                         break;
1262                                 }
1263                         }
1264                         if (!cur) {
1265                                 /* We found a parking space. */
1266                                 parking_space = i;
1267                                 break;
1268                         }
1269                 }
1270                 if (parking_space == -1) {
1271                         /* We did not find a parking space.  Lot is full. */
1272                         ast_log(LOG_WARNING, "No more parking spaces in %s\n", parkinglot->name);
1273                         AST_LIST_UNLOCK(&parkinglot->parkings);
1274                         parkinglot_unref(parkinglot);
1275                         ast_free(pu);
1276                         return NULL;
1277                 }
1278         }
1279
1280         /* Prepare for next parking space search. */
1281         parkinglot->next_parking_space = parking_space + 1;
1282
1283         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
1284         pu->notquiteyet = 1;
1285         pu->parkingnum = parking_space;
1286         pu->parkinglot = parkinglot;
1287         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
1288
1289         return pu;
1290 }
1291
1292 /* Park a call */
1293 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
1294 {
1295         struct parkeduser *pu = args->pu;
1296         const char *event_from;         /*!< Channel name that is parking the call. */
1297         char app_data[AST_MAX_EXTENSION + AST_MAX_CONTEXT];
1298
1299         if (pu == NULL) {
1300                 args->pu = pu = park_space_reserve(chan, peer, args);
1301                 if (pu == NULL) {
1302                         return -1;
1303                 }
1304         }
1305
1306         ast_channel_appl_set(chan, "Parked Call");
1307         ast_channel_data_set(chan, NULL);
1308
1309         pu->chan = chan;
1310
1311         /* Put the parked channel on hold if we have two different channels */
1312         if (chan != peer) {
1313                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1314                         pu->hold_method = AST_CONTROL_RINGING;
1315                         ast_indicate(chan, AST_CONTROL_RINGING);
1316                 } else {
1317                         pu->hold_method = AST_CONTROL_HOLD;
1318                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1319                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1320                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1321                 }
1322         }
1323
1324         pu->start = ast_tvnow();
1325         /* XXX This line was changed to not use get_parkingtime. This is just a placeholder message, because
1326          * likely this entire function is going away.
1327          */
1328         pu->parkingtime = args->timeout;
1329         if (args->extout)
1330                 *(args->extout) = pu->parkingnum;
1331
1332         if (peer) {
1333                 event_from = S_OR(args->orig_chan_name, ast_channel_name(peer));
1334
1335                 /*
1336                  * This is so ugly that it hurts, but implementing
1337                  * get_base_channel() on local channels could have ugly side
1338                  * effects.  We could have
1339                  * transferer<->local;1<->local;2<->parking and we need the
1340                  * callback name to be that of transferer.  Since local;1/2 have
1341                  * the same name we can be tricky and just grab the bridged
1342                  * channel from the other side of the local.
1343                  */
1344                 if (!strcasecmp(ast_channel_tech(peer)->type, "Local")) {
1345                         struct ast_channel *tmpchan, *base_peer;
1346                         char other_side[AST_CHANNEL_NAME];
1347                         char *c;
1348
1349                         ast_copy_string(other_side, event_from, sizeof(other_side));
1350                         if ((c = strrchr(other_side, ';'))) {
1351                                 *++c = '1';
1352                         }
1353                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
1354                                 ast_channel_lock(tmpchan);
1355                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
1356                                         ast_copy_string(pu->peername, ast_channel_name(base_peer), sizeof(pu->peername));
1357                                 }
1358                                 ast_channel_unlock(tmpchan);
1359                                 tmpchan = ast_channel_unref(tmpchan);
1360                         }
1361                 } else {
1362                         ast_copy_string(pu->peername, event_from, sizeof(pu->peername));
1363                 }
1364         } else {
1365                 event_from = S_OR(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"),
1366                         ast_channel_name(chan));
1367         }
1368
1369         /*
1370          * Remember what had been dialed, so that if the parking
1371          * expires, we try to come back to the same place
1372          */
1373         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
1374
1375         /*
1376          * If extension has options specified, they override all other
1377          * possibilities such as the returntoorigin flag and transferred
1378          * context.  Information on extension options is lost here, so
1379          * we set a flag
1380          */
1381         ast_copy_string(pu->context,
1382                 S_OR(args->return_con, S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan))),
1383                 sizeof(pu->context));
1384         ast_copy_string(pu->exten,
1385                 S_OR(args->return_ext, S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan))),
1386                 sizeof(pu->exten));
1387         pu->priority = args->return_pri ? args->return_pri :
1388                 (ast_channel_macropriority(chan) ? ast_channel_macropriority(chan) : ast_channel_priority(chan));
1389
1390         /*
1391          * If parking a channel directly, don't quite yet get parking
1392          * running on it.  All parking lot entries are put into the
1393          * parking lot with notquiteyet on.
1394          */
1395         if (peer != chan) {
1396                 pu->notquiteyet = 0;
1397         }
1398
1399         /* Wake up the (presumably select()ing) thread */
1400         pthread_kill(parking_thread, SIGURG);
1401         ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %u seconds\n",
1402                 ast_channel_name(chan), pu->parkingnum, pu->parkinglot->name,
1403                 pu->context, pu->exten, pu->priority, (pu->parkingtime / 1000));
1404
1405         /*** DOCUMENTATION
1406                 <managerEventInstance>
1407                         <synopsis>Raised when a call has been parked.</synopsis>
1408                         <syntax>
1409                                 <parameter name="Exten">
1410                                         <para>The parking lot extension.</para>
1411                                 </parameter>
1412                                 <parameter name="Parkinglot">
1413                                         <para>The name of the parking lot.</para>
1414                                 </parameter>
1415                                 <parameter name="From">
1416                                         <para>The name of the channel that parked the call.</para>
1417                                 </parameter>
1418                         </syntax>
1419                         <see-also>
1420                                 <ref type="application">Park</ref>
1421                                 <ref type="manager">Park</ref>
1422                                 <ref type="managerEvent">ParkedCallTimeOut</ref>
1423                                 <ref type="managerEvent">ParkedCallGiveUp</ref>
1424                         </see-also>
1425                 </managerEventInstance>
1426         ***/
1427         ast_manager_event(chan, EVENT_FLAG_CALL, "ParkedCall",
1428                 "Exten: %s\r\n"
1429                 "Channel: %s\r\n"
1430                 "Parkinglot: %s\r\n"
1431                 "From: %s\r\n"
1432                 "Timeout: %ld\r\n"
1433                 "CallerIDNum: %s\r\n"
1434                 "CallerIDName: %s\r\n"
1435                 "ConnectedLineNum: %s\r\n"
1436                 "ConnectedLineName: %s\r\n"
1437                 "Uniqueid: %s\r\n",
1438                 pu->parkingexten, ast_channel_name(chan), pu->parkinglot->name, event_from,
1439                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
1440                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
1441                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
1442                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
1443                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
1444                 ast_channel_uniqueid(chan)
1445                 );
1446         ast_debug(4, "peer: %s\n", peer ? ast_channel_name(peer) : "-No peer-");
1447         ast_debug(4, "args->orig_chan_name: %s\n", args->orig_chan_name ? args->orig_chan_name : "-none-");
1448         ast_debug(4, "pu->peername: %s\n", pu->peername);
1449         ast_debug(4, "AMI ParkedCall Channel: %s\n", ast_channel_name(chan));
1450         ast_debug(4, "AMI ParkedCall From: %s\n", event_from);
1451
1452         if (peer && adsipark && ast_adsi_available(peer)) {
1453                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
1454                 ast_adsi_unload_session(peer);
1455         }
1456
1457         snprintf(app_data, sizeof(app_data), "%s,%s", pu->parkingexten,
1458                 pu->parkinglot->name);
1459
1460         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
1461
1462         /* Only say number if it's a number and the channel hasn't been masqueraded away */
1463         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE)
1464                 && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(ast_channel_name(peer), args->orig_chan_name))) {
1465                 /*
1466                  * If a channel is masqueraded into peer while playing back the
1467                  * parking space number do not continue playing it back.  This
1468                  * is the case if an attended transfer occurs.
1469                  */
1470                 ast_set_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1471                 /* Tell the peer channel the number of the parking space */
1472                 ast_say_digits(peer, pu->parkingnum, "", ast_channel_language(peer));
1473                 ast_clear_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1474         }
1475         if (peer == chan) { /* pu->notquiteyet = 1 */
1476                 /* Wake up parking thread if we're really done */
1477                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1478                         pu->hold_method = AST_CONTROL_RINGING;
1479                         ast_indicate(chan, AST_CONTROL_RINGING);
1480                 } else {
1481                         pu->hold_method = AST_CONTROL_HOLD;
1482                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1483                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1484                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1485                 }
1486                 pu->notquiteyet = 0;
1487                 pthread_kill(parking_thread, SIGURG);
1488         }
1489         return 0;
1490 }
1491
1492 int ast_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
1493 {
1494         int res;
1495         char *parse;
1496         const char *app_data;
1497         struct ast_exten *exten;
1498         struct park_app_args app_args;
1499         struct ast_park_call_args args = {
1500                 .timeout = timeout,
1501                 .extout = extout,
1502         };
1503
1504         if (!park_exten || !park_context) {
1505                 return park_call_full(park_me, parker, &args);
1506         }
1507
1508         /*
1509          * Determiine if the specified park extension has an exclusive
1510          * parking lot to use.
1511          */
1512         if (parker && parker != park_me) {
1513                 ast_autoservice_start(park_me);
1514         }
1515         exten = get_parking_exten(park_exten, parker, park_context);
1516         if (exten) {
1517                 app_data = ast_get_extension_app_data(exten);
1518                 if (!app_data) {
1519                         app_data = "";
1520                 }
1521                 parse = ast_strdupa(app_data);
1522                 AST_STANDARD_APP_ARGS(app_args, parse);
1523
1524                 if (!ast_strlen_zero(app_args.pl_name)) {
1525                         /* Find the specified exclusive parking lot */
1526                         args.parkinglot = find_parkinglot(app_args.pl_name);
1527                         if (!args.parkinglot && parkeddynamic) {
1528                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1529                         }
1530                 }
1531         }
1532         if (parker && parker != park_me) {
1533                 ast_autoservice_stop(park_me);
1534         }
1535
1536         res = park_call_full(park_me, parker, &args);
1537         if (args.parkinglot) {
1538                 parkinglot_unref(args.parkinglot);
1539         }
1540         return res;
1541 }
1542
1543 int ast_park_call(struct ast_channel *park_me, struct ast_channel *parker, int timeout, const char *park_exten, int *extout)
1544 {
1545         struct ast_park_call_args args = {
1546                 .timeout = timeout,
1547                 .extout = extout,
1548         };
1549
1550         return park_call_full(park_me, parker, &args);
1551 }
1552
1553 /*!
1554  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
1555  *
1556  * \param rchan the real channel to be parked
1557  * \param peer the channel to have the parking read to.
1558  * \param args Additional parking options when parking a call.
1559  *
1560  * \retval 0 on success.
1561  * \retval -1 on failure.
1562  */
1563 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1564 {
1565         struct ast_channel *chan;
1566
1567         /* Make a new, channel that we'll use to masquerade in the real one */
1568         chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(rchan), ast_channel_exten(rchan),
1569                 ast_channel_context(rchan), ast_channel_linkedid(rchan), ast_channel_amaflags(rchan), "Parked/%s", ast_channel_name(rchan));
1570         if (!chan) {
1571                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1572                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1573                         if (peer == rchan) {
1574                                 /* Only have one channel to worry about. */
1575                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1576                         } else if (peer) {
1577                                 /* Have two different channels to worry about. */
1578                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1579                         }
1580                 }
1581                 return -1;
1582         }
1583
1584         args->pu = park_space_reserve(rchan, peer, args);
1585         if (!args->pu) {
1586                 ast_hangup(chan);
1587                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1588                         if (peer == rchan) {
1589                                 /* Only have one channel to worry about. */
1590                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1591                         } else if (peer) {
1592                                 /* Have two different channels to worry about. */
1593                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1594                         }
1595                 }
1596                 return -1;
1597         }
1598
1599         /* Make formats okay */
1600         ast_format_copy(ast_channel_readformat(chan), ast_channel_readformat(rchan));
1601         ast_format_copy(ast_channel_writeformat(chan), ast_channel_writeformat(rchan));
1602
1603         if (ast_channel_masquerade(chan, rchan)) {
1604                 park_space_abort(args->pu);
1605                 args->pu = NULL;
1606                 ast_hangup(chan);
1607                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1608                         if (peer == rchan) {
1609                                 /* Only have one channel to worry about. */
1610                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1611                         } else if (peer) {
1612                                 /* Have two different channels to worry about. */
1613                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1614                         }
1615                 }
1616                 return -1;
1617         }
1618
1619         /* Setup the extensions and such */
1620         set_c_e_p(chan, ast_channel_context(rchan), ast_channel_exten(rchan), ast_channel_priority(rchan));
1621
1622         /* Setup the macro extension and such */
1623         ast_channel_macrocontext_set(chan, ast_channel_macrocontext(rchan));
1624         ast_channel_macroexten_set(chan, ast_channel_macroexten(rchan));
1625         ast_channel_macropriority_set(chan, ast_channel_macropriority(rchan));
1626
1627         /* Manually do the masquerade to make sure it is complete. */
1628         ast_do_masquerade(chan);
1629
1630         if (peer == rchan) {
1631                 peer = chan;
1632         }
1633
1634         /* parking space reserved, return code check unnecessary */
1635         park_call_full(chan, peer, args);
1636
1637         return 0;
1638 }
1639
1640 int ast_masq_park_call_exten(struct ast_channel *park_me, struct ast_channel *parker, const char *park_exten, const char *park_context, int timeout, int *extout)
1641 {
1642         int res;
1643         char *parse;
1644         const char *app_data;
1645         struct ast_exten *exten;
1646         struct park_app_args app_args;
1647         struct ast_park_call_args args = {
1648                 .timeout = timeout,
1649                 .extout = extout,
1650         };
1651
1652         if (parker) {
1653                 args.orig_chan_name = ast_strdupa(ast_channel_name(parker));
1654         }
1655         if (!park_exten || !park_context) {
1656                 return masq_park_call(park_me, parker, &args);
1657         }
1658
1659         /*
1660          * Determiine if the specified park extension has an exclusive
1661          * parking lot to use.
1662          */
1663         if (parker && parker != park_me) {
1664                 ast_autoservice_start(park_me);
1665         }
1666         exten = get_parking_exten(park_exten, parker, park_context);
1667         if (exten) {
1668                 app_data = ast_get_extension_app_data(exten);
1669                 if (!app_data) {
1670                         app_data = "";
1671                 }
1672                 parse = ast_strdupa(app_data);
1673                 AST_STANDARD_APP_ARGS(app_args, parse);
1674
1675                 if (!ast_strlen_zero(app_args.pl_name)) {
1676                         /* Find the specified exclusive parking lot */
1677                         args.parkinglot = find_parkinglot(app_args.pl_name);
1678                         if (!args.parkinglot && parkeddynamic) {
1679                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1680                         }
1681                 }
1682         }
1683         if (parker && parker != park_me) {
1684                 ast_autoservice_stop(park_me);
1685         }
1686
1687         res = masq_park_call(park_me, parker, &args);
1688         if (args.parkinglot) {
1689                 parkinglot_unref(args.parkinglot);
1690         }
1691         return res;
1692 }
1693
1694 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1695 {
1696         struct ast_park_call_args args = {
1697                 .timeout = timeout,
1698                 .extout = extout,
1699         };
1700
1701         if (peer) {
1702                 args.orig_chan_name = ast_strdupa(ast_channel_name(peer));
1703         }
1704         return masq_park_call(rchan, peer, &args);
1705 }
1706
1707 #if 0
1708 static int finishup(struct ast_channel *chan)
1709 {
1710         ast_indicate(chan, AST_CONTROL_UNHOLD);
1711
1712         return ast_autoservice_stop(chan);
1713 }
1714 #endif
1715
1716 #if 0
1717 /*!
1718  * \internal
1719  * \brief Builtin transfer park call helper.
1720  *
1721  * \param park_me Channel to be parked.
1722  * \param parker Channel parking the call.
1723  * \param park_exten Parking lot dialplan access ramp extension.
1724  *
1725  * \note Assumes park_me is on hold and in autoservice.
1726  *
1727  * \retval -1 on successful park.
1728  * \retval -1 on park_me hangup.
1729  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
1730  */
1731 static int xfer_park_call_helper(struct ast_channel *park_me, struct ast_channel *parker, struct ast_exten *park_exten)
1732 {
1733         char *parse;
1734         const char *app_data;
1735         const char *pl_name;
1736         struct ast_park_call_args args = { 0, };
1737         struct park_app_args app_args;
1738         int res;
1739
1740         app_data = ast_get_extension_app_data(park_exten);
1741         if (!app_data) {
1742                 app_data = "";
1743         }
1744         parse = ast_strdupa(app_data);
1745         AST_STANDARD_APP_ARGS(app_args, parse);
1746
1747         /* Find the parking lot */
1748         if (!ast_strlen_zero(app_args.pl_name)) {
1749                 pl_name = app_args.pl_name;
1750         } else {
1751                 pl_name = findparkinglotname(parker);
1752         }
1753         if (ast_strlen_zero(pl_name)) {
1754                 /* Parking lot is not specified, so use the default parking lot. */
1755                 args.parkinglot = parkinglot_addref(default_parkinglot);
1756         } else {
1757                 args.parkinglot = find_parkinglot(pl_name);
1758                 if (!args.parkinglot && parkeddynamic) {
1759                         args.parkinglot = create_dynamic_parkinglot(pl_name, park_me);
1760                 }
1761         }
1762
1763         if (args.parkinglot) {
1764                 /* Park the call */
1765                 res = finishup(park_me);
1766                 if (res) {
1767                         /* park_me hungup on us. */
1768                         parkinglot_unref(args.parkinglot);
1769                         return -1;
1770                 }
1771                 res = masq_park_call(park_me, parker, &args);
1772                 parkinglot_unref(args.parkinglot);
1773         } else {
1774                 /* Parking failed because parking lot does not exist. */
1775                 if (!ast_test_flag(&args, AST_PARK_OPT_SILENCE)) {
1776                         ast_stream_and_wait(parker, "pbx-parkingfailed", "");
1777                 }
1778                 finishup(park_me);
1779                 res = -1;
1780         }
1781
1782         return res ? AST_FEATURE_RETURN_SUCCESS : -1;
1783 }
1784 #endif
1785
1786 #if 0
1787 /*!
1788  * \brief set caller and callee according to the direction
1789  * \param caller, callee, peer, chan, sense
1790  *
1791  * Detect who triggered feature and set callee/caller variables accordingly
1792  */
1793 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
1794         struct ast_channel *peer, struct ast_channel *chan, int sense)
1795 {
1796         if (sense == FEATURE_SENSE_PEER) {
1797                 *caller = peer;
1798                 *callee = chan;
1799         } else {
1800                 *callee = peer;
1801                 *caller = chan;
1802         }
1803 }
1804 #endif
1805
1806 #if 0
1807 /*!
1808  * \brief support routing for one touch call parking
1809  * \param chan channel parking call
1810  * \param peer channel to be parked
1811  * \param config unsed
1812  * \param code unused
1813  * \param sense feature options
1814  * \param data unused
1815  *
1816  * \retval -1 on successful park.
1817  * \retval -1 on chan hangup.
1818  * \retval AST_FEATURE_RETURN_SUCCESS on error to keep the bridge connected.
1819  */
1820 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1821 {
1822         struct ast_channel *parker;
1823         struct ast_channel *parkee;
1824         struct ast_park_call_args args = { 0, };
1825
1826         /*
1827          * We used to set chan's exten and priority to "s" and 1 here,
1828          * but this generates (in some cases) an invalid extension, and
1829          * if "s" exists, could errantly cause execution of extensions
1830          * you don't expect.  It makes more sense to let nature take its
1831          * course when chan finishes, and let the pbx do its thing and
1832          * hang up when the park is over.
1833          */
1834
1835         /* Answer if call is not up */
1836         if (ast_channel_state(chan) != AST_STATE_UP) {
1837                 /*
1838                  * XXX Why are we doing this?  Both of the channels should be up
1839                  * since you cannot do DTMF features unless you are bridged.
1840                  */
1841                 if (ast_answer(chan)) {
1842                         return -1;
1843                 }
1844
1845                 /* Sleep to allow VoIP streams to settle down */
1846                 if (ast_safe_sleep(chan, 1000)) {
1847                         return -1;
1848                 }
1849         }
1850
1851         /* one direction used to call park_call.... */
1852         set_peers(&parker, &parkee, peer, chan, sense);
1853         return masq_park_call(parkee, parker, &args) ? AST_FEATURE_RETURN_SUCCESS : -1;
1854 }
1855 #endif
1856
1857 /*!
1858  * \internal
1859  * \brief Play file to specified channel.
1860  *
1861  * \param play_to Channel to play audiofile to.
1862  * \param other Channel to put in autoservice while playing file.
1863  * \param msg Descriptive name of message type being played.
1864  * \param audiofile Audio file to play.
1865  *
1866  * \retval 0 on success.
1867  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
1868  */
1869 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
1870 {
1871         /* Put other channel in autoservice. */
1872         if (ast_autoservice_start(other)) {
1873                 return -1;
1874         }
1875         ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
1876         ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
1877         if (ast_stream_and_wait(play_to, audiofile, "")) {
1878                 ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
1879                 ast_autoservice_stop(other);
1880                 return -1;
1881         }
1882         if (ast_autoservice_stop(other)) {
1883                 return -1;
1884         }
1885         return 0;
1886 }
1887
1888 #if 0
1889 /*!
1890  * \internal
1891  * \brief Play file to specified channels.
1892  *
1893  * \param left Channel on left to play file.
1894  * \param right Channel on right to play file.
1895  * \param which Play file on indicated channels: which < 0 play left, which == 0 play both, which > 0 play right
1896  * \param msg Descriptive name of message type being played.
1897  * \param audiofile Audio file to play to channels.
1898  *
1899  * \note Plays file to the indicated channels in turn so please
1900  * don't use this for very long messages.
1901  *
1902  * \retval 0 on success.
1903  * \retval -1 on error. (Couldn't play file, channel hung up,...)
1904  */
1905 static int play_message_to_chans(struct ast_channel *left, struct ast_channel *right, int which, const char *msg, const char *audiofile)
1906 {
1907         /* First play the file to the left channel if requested. */
1908         if (which <= 0 && play_message_on_chan(left, right, msg, audiofile)) {
1909                 return -1;
1910         }
1911
1912         /* Then play the file to the right channel if requested. */
1913         if (which >= 0 && play_message_on_chan(right, left, msg, audiofile)) {
1914                 return -1;
1915         }
1916
1917         return 0;
1918 }
1919 #endif
1920
1921 #if 0
1922 /*!
1923  * \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
1924  * other channel during the message, so please don't use this for very long messages
1925  */
1926 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
1927 {
1928         return play_message_to_chans(caller_chan, callee_chan, 0, "automon message",
1929                 audiofile);
1930 }
1931 #endif
1932
1933 #if 0
1934 /*!
1935  * \brief Monitor a channel by DTMF
1936  * \param chan channel requesting monitor
1937  * \param peer channel to be monitored
1938  * \param config
1939  * \param code
1940  * \param sense feature options
1941  *
1942  * \param data
1943  * Check monitor app enabled, setup channels, both caller/callee chans not null
1944  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
1945  * \retval AST_FEATURE_RETURN_SUCCESS on success.
1946  * \retval -1 on error.
1947  */
1948 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1949 {
1950         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1951         int x = 0;
1952         size_t len;
1953         struct ast_channel *caller_chan, *callee_chan;
1954         const char *automon_message_start = NULL;
1955         const char *automon_message_stop = NULL;
1956         const char *touch_format = NULL;
1957         const char *touch_monitor = NULL;
1958         const char *touch_monitor_prefix = NULL;
1959         struct ast_app *monitor_app;
1960
1961         monitor_app = pbx_findapp("Monitor");
1962         if (!monitor_app) {
1963                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1964                 return -1;
1965         }
1966
1967         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1968
1969         /* Find extra messages */
1970         automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1971         automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1972
1973         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1974                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1975                         return -1;
1976                 }
1977         }
1978
1979         if (ast_channel_monitor(callee_chan)) {
1980                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1981                 if (!ast_strlen_zero(automon_message_stop)) {
1982                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1983                 }
1984                 ast_channel_monitor(callee_chan)->stop(callee_chan, 1);
1985                 return AST_FEATURE_RETURN_SUCCESS;
1986         }
1987
1988         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1989         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1990         touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1991
1992         if (!touch_format)
1993                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1994
1995         if (!touch_monitor)
1996                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1997
1998         if (!touch_monitor_prefix)
1999                 touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
2000
2001         if (touch_monitor) {
2002                 len = strlen(touch_monitor) + 50;
2003                 args = ast_alloca(len);
2004                 touch_filename = ast_alloca(len);
2005                 snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
2006                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2007         } else {
2008                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2009                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2010                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2011                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2012                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2013                 args = ast_alloca(len);
2014                 touch_filename = ast_alloca(len);
2015                 snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
2016                 snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
2017         }
2018
2019         for(x = 0; x < strlen(args); x++) {
2020                 if (args[x] == '/')
2021                         args[x] = '-';
2022         }
2023
2024         ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
2025
2026         pbx_exec(callee_chan, monitor_app, args);
2027         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2028         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
2029
2030         if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
2031                 play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
2032         }
2033
2034         return AST_FEATURE_RETURN_SUCCESS;
2035 }
2036 #endif
2037
2038 #if 0
2039 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2040 {
2041         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
2042         int x = 0;
2043         size_t len;
2044         struct ast_channel *caller_chan, *callee_chan;
2045         const char *mixmonitor_spy_type = "MixMonitor";
2046         const char *touch_format;
2047         const char *touch_monitor;
2048         struct ast_app *mixmonitor_app;
2049         int count = 0;
2050
2051         mixmonitor_app = pbx_findapp("MixMonitor");
2052         if (!mixmonitor_app) {
2053                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
2054                 return -1;
2055         }
2056
2057         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
2058
2059         if (!ast_strlen_zero(courtesytone)) {
2060                 if (ast_autoservice_start(callee_chan))
2061                         return -1;
2062                 ast_autoservice_ignore(callee_chan, AST_FRAME_DTMF_END);
2063                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
2064                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
2065                         ast_autoservice_stop(callee_chan);
2066                         return -1;
2067                 }
2068                 if (ast_autoservice_stop(callee_chan))
2069                         return -1;
2070         }
2071
2072         ast_channel_lock(callee_chan);
2073         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2074         ast_channel_unlock(callee_chan);
2075
2076         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
2077         if (count > 0) {
2078                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
2079
2080                 /* Make sure they are running */
2081                 ast_channel_lock(callee_chan);
2082                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
2083                 ast_channel_unlock(callee_chan);
2084                 if (count > 0) {
2085                         struct ast_app *stopmixmonitor_app;
2086
2087                         stopmixmonitor_app = pbx_findapp("StopMixMonitor");
2088                         if (!stopmixmonitor_app) {
2089                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
2090                                 return -1;
2091                         }
2092                         pbx_exec(callee_chan, stopmixmonitor_app, "");
2093                         return AST_FEATURE_RETURN_SUCCESS;
2094                 }
2095
2096                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");
2097         }
2098
2099         touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
2100         touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
2101
2102         if (!touch_format)
2103                 touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
2104
2105         if (!touch_monitor)
2106                 touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
2107
2108         if (touch_monitor) {
2109                 len = strlen(touch_monitor) + 50;
2110                 args = ast_alloca(len);
2111                 touch_filename = ast_alloca(len);
2112                 snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
2113                 snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
2114         } else {
2115                 caller_chan_id = ast_strdupa(S_COR(ast_channel_caller(caller_chan)->id.number.valid,
2116                         ast_channel_caller(caller_chan)->id.number.str, ast_channel_name(caller_chan)));
2117                 callee_chan_id = ast_strdupa(S_COR(ast_channel_caller(callee_chan)->id.number.valid,
2118                         ast_channel_caller(callee_chan)->id.number.str, ast_channel_name(callee_chan)));
2119                 len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
2120                 args = ast_alloca(len);
2121                 touch_filename = ast_alloca(len);
2122                 snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
2123                 snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
2124         }
2125
2126         for( x = 0; x < strlen(args); x++) {
2127                 if (args[x] == '/')
2128                         args[x] = '-';
2129         }
2130
2131         ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
2132
2133         pbx_exec(callee_chan, mixmonitor_app, args);
2134         pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2135         pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
2136         return AST_FEATURE_RETURN_SUCCESS;
2137 }
2138 #endif
2139
2140 #if 0
2141 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2142 {
2143         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
2144         return AST_FEATURE_RETURN_HANGUP;
2145 }
2146 #endif
2147
2148 #if 0
2149 /*!
2150  * \brief Find the context for the transfer
2151  * \param transferer
2152  * \param transferee
2153  *
2154  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
2155  * \return a context string
2156  */
2157 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
2158 {
2159         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
2160         if (ast_strlen_zero(s)) {
2161                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
2162         }
2163         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
2164                 s = ast_channel_macrocontext(transferer);
2165         }
2166         if (ast_strlen_zero(s)) {
2167                 s = ast_channel_context(transferer);
2168         }
2169         return s;
2170 }
2171 #endif
2172
2173 #if 0
2174 /*!
2175  * \brief make channels compatible
2176  * \param c
2177  * \param newchan
2178  * \retval 0 on success.
2179  * \retval -1 on failure.
2180  */
2181 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
2182 {
2183         if (ast_channel_make_compatible(c, newchan) < 0) {
2184                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
2185                         ast_channel_name(c), ast_channel_name(newchan));
2186                 ast_autoservice_chan_hangup_peer(c, newchan);
2187                 return -1;
2188         }
2189         return 0;
2190 }
2191 #endif
2192
2193 #if 0
2194 /*!
2195  * \internal
2196  * \brief Builtin attended transfer failed cleanup.
2197  * \since 10.0
2198  *
2199  * \param transferee Party A in the transfer.
2200  * \param transferer Party B in the transfer.
2201  * \param connected_line Saved connected line info about party A.
2202  *
2203  * \note The connected_line data is freed.
2204  *
2205  * \return Nothing
2206  */
2207 static void atxfer_fail_cleanup(struct ast_channel *transferee, struct ast_channel *transferer, struct ast_party_connected_line *connected_line)
2208 {
2209         finishup(transferee);
2210
2211         /*
2212          * Restore party B connected line info about party A.
2213          *
2214          * Party B was the caller to party C and is the last known mode
2215          * for party B.
2216          */
2217         if (ast_channel_connected_line_sub(transferee, transferer, connected_line, 0) &&
2218                 ast_channel_connected_line_macro(transferee, transferer, connected_line, 1, 0)) {
2219                 ast_channel_update_connected_line(transferer, connected_line, NULL);
2220         }
2221         ast_party_connected_line_free(connected_line);
2222 }
2223 #endif
2224
2225 #if 0
2226 /*!
2227  * \brief Attended transfer
2228  * \param chan transfered user
2229  * \param peer person transfering call
2230  * \param config
2231  * \param code
2232  * \param sense feature options
2233  *
2234  * \param data
2235  * Get extension to transfer to, if you cannot generate channel (or find extension)
2236  * return to host channel. After called channel answered wait for hangup of transferer,
2237  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
2238  *
2239  * \return -1 on failure
2240  */
2241 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2242 {
2243         struct ast_channel *transferer;/* Party B */
2244         struct ast_channel *transferee;/* Party A */
2245         struct ast_exten *park_exten;
2246         const char *chan1_attended_sound;
2247         const char *chan2_attended_sound;
2248         const char *transferer_real_context;
2249         char xferto[256] = "";
2250         int res;
2251         int outstate=0;
2252         struct ast_channel *newchan;
2253         struct ast_channel *xferchan;
2254         struct ast_bridge_thread_obj *tobj;
2255         struct ast_bridge_config bconfig;
2256         int l;
2257         struct ast_party_connected_line connected_line;
2258         struct ast_datastore *features_datastore;
2259         struct ast_dial_features *dialfeatures;
2260         char *transferer_tech;
2261         char *transferer_name;
2262         char *transferer_name_orig;
2263         char *dash;
2264         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
2265
2266         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", ast_channel_name(chan), ast_channel_name(peer), sense);
2267         set_peers(&transferer, &transferee, peer, chan, sense);
2268         transferer_real_context = real_ctx(transferer, transferee);
2269
2270         /* Start autoservice on transferee while we talk to the transferer */
2271         ast_autoservice_start(transferee);
2272         ast_indicate(transferee, AST_CONTROL_HOLD);
2273
2274         /* Transfer */
2275         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
2276         if (res < 0) {
2277                 finishup(transferee);
2278                 return -1;
2279         }
2280         if (res > 0) { /* If they've typed a digit already, handle it */
2281                 xferto[0] = (char) res;
2282         }
2283
2284         ast_channel_lock(transferer);
2285         xfer_cfg = ast_get_chan_features_xfer_config(transferer);
2286         ast_channel_unlock(transferer);
2287
2288         /* XXX All accesses to the xfer_cfg structure after this point are not thread-safe,
2289          * but I don't care because this is dead code.
2290          */
2291
2292         /* this is specific of atxfer */
2293         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, xfer_cfg->transferdigittimeout);
2294         if (res < 0) {  /* hangup or error, (would be 0 for invalid and 1 for valid) */
2295                 finishup(transferee);
2296                 return -1;
2297         }
2298         l = strlen(xferto);
2299         if (res == 0) {
2300                 if (l) {
2301                         ast_log(LOG_WARNING, "Extension '%s' does not exist in context '%s'\n",
2302                                 xferto, transferer_real_context);
2303                 } else {
2304                         /* Does anyone care about this case? */
2305                         ast_log(LOG_WARNING, "No digits dialed for atxfer.\n");
2306                 }
2307                 ast_stream_and_wait(transferer, "pbx-invalid", "");
2308                 finishup(transferee);
2309                 return AST_FEATURE_RETURN_SUCCESS;
2310         }
2311
2312         park_exten = get_parking_exten(xferto, transferer, transferer_real_context);
2313         if (park_exten) {
2314                 /* We are transfering the transferee to a parking lot. */
2315                 return xfer_park_call_helper(transferee, transferer, park_exten);
2316         }
2317
2318         /*
2319          * Append context to dialed transfer number.
2320          *
2321          * NOTE: The local channel needs the /n flag so party C will use
2322          * the feature flags set by the dialplan when calling that
2323          * party.
2324          */
2325         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);
2326
2327         /* If we are performing an attended transfer and we have two channels involved then
2328            copy sound file information to play upon attended transfer completion */
2329         chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2330         chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
2331         if (!ast_strlen_zero(chan1_attended_sound)) {
2332                 pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
2333         }
2334         if (!ast_strlen_zero(chan2_attended_sound)) {
2335                 pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
2336         }
2337
2338         /* Extract redial transferer information from the channel name. */
2339         transferer_name_orig = ast_strdupa(ast_channel_name(transferer));
2340         transferer_name = ast_strdupa(transferer_name_orig);
2341         transferer_tech = strsep(&transferer_name, "/");
2342         dash = strrchr(transferer_name, '-');
2343         if (dash) {
2344                 /* Trim off channel name sequence/serial number. */
2345                 *dash = '\0';
2346         }
2347
2348         /* Stop autoservice so we can monitor all parties involved in the transfer. */
2349         if (ast_autoservice_stop(transferee) < 0) {
2350                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2351                 return -1;
2352         }
2353
2354         /* Save connected line info for party B about party A in case transfer fails. */
2355         ast_party_connected_line_init(&connected_line);
2356         ast_channel_lock(transferer);
2357         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2358         ast_channel_unlock(transferer);
2359         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2360
2361         /* Dial party C */
2362         newchan = feature_request_and_dial(transferer, transferer_name_orig, transferer,
2363                 transferee, "Local", ast_channel_nativeformats(transferer), xferto,
2364                 xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2365         ast_debug(2, "Dial party C result: newchan:%d, outstate:%d\n", !!newchan, outstate);
2366
2367         if (!ast_check_hangup(transferer)) {
2368                 /* Transferer (party B) is up */
2369                 ast_debug(1, "Actually doing an attended transfer.\n");
2370
2371                 /* Start autoservice on transferee while the transferer deals with party C. */
2372                 ast_autoservice_start(transferee);
2373
2374                 ast_indicate(transferer, -1);
2375                 if (!newchan) {
2376                         /* any reason besides user requested cancel and busy triggers the failed sound */
2377                         switch (outstate) {
2378                         case AST_CONTROL_UNHOLD:/* Caller requested cancel or party C answer timeout. */
2379                         case AST_CONTROL_BUSY:
2380                         case AST_CONTROL_CONGESTION:
2381                                 if (ast_stream_and_wait(transferer, xfer_cfg->xfersound, "")) {
2382                                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2383                                 }
2384                                 break;
2385                         default:
2386                                 if (ast_stream_and_wait(transferer, xfer_cfg->xferfailsound, "")) {
2387                                         ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2388                                 }
2389                                 break;
2390                         }
2391                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2392                         return AST_FEATURE_RETURN_SUCCESS;
2393                 }
2394
2395                 if (check_compat(transferer, newchan)) {
2396                         if (ast_stream_and_wait(transferer, xfer_cfg->xferfailsound, "")) {
2397                                 ast_log(LOG_WARNING, "Failed to play transfer failed sound!\n");
2398                         }
2399                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2400                         return AST_FEATURE_RETURN_SUCCESS;
2401                 }
2402                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
2403                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
2404                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
2405
2406                 /*
2407                  * Let party B and C talk as long as they want while party A
2408                  * languishes in autoservice listening to MOH.
2409                  */
2410                 ast_bridge_call(transferer, newchan, &bconfig);
2411
2412                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
2413                         ast_autoservice_chan_hangup_peer(transferer, newchan);
2414                         if (ast_stream_and_wait(transferer, xfer_cfg->xfersound, "")) {
2415                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2416                         }
2417                         atxfer_fail_cleanup(transferee, transferer, &connected_line);
2418                         return AST_FEATURE_RETURN_SUCCESS;
2419                 }
2420
2421                 /* Transferer (party B) is confirmed hung up at this point. */
2422                 if (check_compat(transferee, newchan)) {
2423                         finishup(transferee);
2424                         ast_party_connected_line_free(&connected_line);
2425                         return -1;
2426                 }
2427
2428                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2429                 if ((ast_autoservice_stop(transferee) < 0)
2430                         || (ast_waitfordigit(transferee, 100) < 0)
2431                         || (ast_waitfordigit(newchan, 100) < 0)
2432                         || ast_check_hangup(transferee)
2433                         || ast_check_hangup(newchan)) {
2434                         ast_hangup(newchan);
2435                         ast_party_connected_line_free(&connected_line);
2436                         return -1;
2437                 }
2438         } else if (!ast_check_hangup(transferee)) {
2439                 /* Transferer (party B) has hung up at this point.  Doing blonde transfer. */
2440                 ast_debug(1, "Actually doing a blonde transfer.\n");
2441
2442                 if (!newchan && !xfer_cfg->atxferdropcall) {
2443                         /* Party C is not available, try to call party B back. */
2444                         unsigned int tries = 0;
2445
2446                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2447                                 ast_log(LOG_WARNING,
2448                                         "Transferer channel name: '%s' cannot be used for callback.\n",
2449                                         transferer_name_orig);
2450                                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2451                                 ast_party_connected_line_free(&connected_line);
2452                                 return -1;
2453                         }
2454
2455                         tries = 0;
2456                         for (;;) {
2457                                 /* Try to get party B back. */
2458                                 ast_debug(1, "We're trying to callback %s/%s\n",
2459                                         transferer_tech, transferer_name);
2460                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2461                                         transferee, transferee, transferer_tech,
2462                                         ast_channel_nativeformats(transferee), transferer_name,
2463                                         xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2464                                 ast_debug(2, "Dial party B result: newchan:%d, outstate:%d\n",
2465                                         !!newchan, outstate);
2466                                 if (newchan) {
2467                                         /*
2468                                          * We have recalled party B (newchan).  We need to give this
2469                                          * call leg the same feature flags as the original party B call
2470                                          * leg.
2471                                          */
2472                                         ast_channel_lock(transferer);
2473                                         features_datastore = ast_channel_datastore_find(transferer,
2474                                                 &dial_features_info, NULL);
2475                                         if (features_datastore && (dialfeatures = features_datastore->data)) {
2476                                                 struct ast_flags my_features = { 0 };
2477                                                 struct ast_flags peer_features = { 0 };
2478
2479                                                 ast_copy_flags(&my_features, &dialfeatures->my_features,
2480                                                         AST_FLAGS_ALL);
2481                                                 ast_copy_flags(&peer_features, &dialfeatures->peer_features,
2482                                                         AST_FLAGS_ALL);
2483                                                 ast_channel_unlock(transferer);
2484                                                 add_features_datastore(newchan, &my_features, &peer_features);
2485                                         } else {
2486                                                 ast_channel_unlock(transferer);
2487                                         }
2488                                         break;
2489                                 }
2490                                 if (ast_check_hangup(transferee)) {
2491                                         break;
2492                                 }
2493
2494                                 ++tries;
2495                                 if (xfer_cfg->atxfercallbackretries <= tries) {
2496                                         /* No more callback tries remaining. */
2497                                         break;
2498                                 }
2499
2500                                 if (xfer_cfg->atxferloopdelay) {
2501                                         /* Transfer failed, sleeping */
2502                                         ast_debug(1, "Sleeping for %d ms before retrying atxfer.\n",
2503                                                 xfer_cfg->atxferloopdelay);
2504                                         ast_safe_sleep(transferee, xfer_cfg->atxferloopdelay);
2505                                         if (ast_check_hangup(transferee)) {
2506                                                 ast_party_connected_line_free(&connected_line);
2507                                                 return -1;
2508                                         }
2509                                 }
2510
2511                                 /* Retry dialing party C. */
2512                                 ast_debug(1, "We're retrying to call %s/%s\n", "Local", xferto);
2513                                 newchan = feature_request_and_dial(transferer, transferer_name_orig,
2514                                         transferer, transferee, "Local",
2515                                         ast_channel_nativeformats(transferee), xferto,
2516                                         xfer_cfg->atxfernoanswertimeout, &outstate, ast_channel_language(transferer));
2517                                 ast_debug(2, "Redial party C result: newchan:%d, outstate:%d\n",
2518                                         !!newchan, outstate);
2519                                 if (newchan || ast_check_hangup(transferee)) {
2520                                         break;
2521                                 }
2522                         }
2523                 }
2524                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2525                 if (!newchan) {
2526                         /* No party C or could not callback party B. */
2527                         ast_party_connected_line_free(&connected_line);
2528                         return -1;
2529                 }
2530
2531                 /* newchan is up, we should prepare transferee and bridge them */
2532                 if (ast_check_hangup(newchan)) {
2533                         ast_autoservice_chan_hangup_peer(transferee, newchan);
2534                         ast_party_connected_line_free(&connected_line);
2535                         return -1;
2536                 }
2537                 if (check_compat(transferee, newchan)) {
2538                         ast_party_connected_line_free(&connected_line);
2539                         return -1;
2540                 }
2541         } else {
2542                 /*
2543                  * Both the transferer and transferee have hungup.  If newchan
2544                  * is up, hang it up as it has no one to talk to.
2545                  */
2546                 ast_debug(1, "Everyone is hungup.\n");
2547                 if (newchan) {
2548                         ast_hangup(newchan);
2549                 }
2550                 ast_party_connected_line_free(&connected_line);
2551                 return -1;
2552         }
2553
2554         /* Initiate the channel transfer of party A to party C (or recalled party B). */
2555         ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2556
2557         xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", ast_channel_linkedid(transferee), 0, "Transfered/%s", ast_channel_name(transferee));
2558         if (!xferchan) {
2559                 ast_autoservice_chan_hangup_peer(transferee, newchan);
2560                 ast_party_connected_line_free(&connected_line);
2561                 return -1;
2562         }
2563
2564         /* Give party A a momentary ringback tone during transfer. */
2565         ast_channel_visible_indication_set(xferchan, AST_CONTROL_RINGING);
2566
2567         /* Make formats okay */
2568         ast_format_copy(ast_channel_readformat(xferchan), ast_channel_readformat(transferee));
2569         ast_format_copy(ast_channel_writeformat(xferchan), ast_channel_writeformat(transferee));
2570
2571         if (ast_channel_masquerade(xferchan, transferee)) {
2572                 ast_hangup(xferchan);
2573                 ast_autoservice_chan_hangup_peer(transferee, newchan);
2574                 ast_party_connected_line_free(&connected_line);
2575                 return -1;
2576         }
2577
2578         dash = strrchr(xferto, '@');
2579         if (dash) {
2580                 /* Trim off the context. */
2581                 *dash = '\0';
2582         }
2583         ast_explicit_goto(xferchan, transferer_real_context, xferto, 1);
2584         ast_channel_state_set(xferchan, AST_STATE_UP);
2585         ast_clear_flag(ast_channel_flags(xferchan), AST_FLAGS_ALL);
2586
2587         /* Do the masquerade manually to make sure that is is completed. */
2588         ast_do_masquerade(xferchan);
2589
2590         ast_channel_state_set(newchan, AST_STATE_UP);
2591         ast_clear_flag(ast_channel_flags(newchan), AST_FLAGS_ALL);
2592         tobj = ast_calloc(1, sizeof(*tobj));
2593         if (!tobj) {
2594                 ast_hangup(xferchan);
2595                 ast_hangup(newchan);
2596                 ast_party_connected_line_free(&connected_line);
2597                 return -1;
2598         }
2599
2600         tobj->chan = newchan;
2601         tobj->peer = xferchan;
2602         tobj->bconfig = *config;
2603
2604         ast_channel_lock(newchan);
2605         features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL);
2606         if (features_datastore && (dialfeatures = features_datastore->data)) {
2607                 ast_copy_flags(&tobj->bconfig.features_callee, &dialfeatures->my_features,
2608                         AST_FLAGS_ALL);
2609         }
2610         ast_channel_unlock(newchan);
2611
2612         ast_channel_lock(xferchan);
2613         features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL);
2614         if (features_datastore && (dialfeatures = features_datastore->data)) {
2615                 ast_copy_flags(&tobj->bconfig.features_caller, &dialfeatures->my_features,
2616                         AST_FLAGS_ALL);
2617         }
2618         ast_channel_unlock(xferchan);
2619
2620         if (tobj->bconfig.end_bridge_callback_data_fixup) {
2621                 tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2622         }
2623
2624         /*
2625          * xferchan is transferee, and newchan is the transfer target
2626          * So...in a transfer, who is the caller and who is the callee?
2627          *
2628          * When the call is originally made, it is clear who is caller and callee.
2629          * When a transfer occurs, it is my humble opinion that the transferee becomes
2630          * the caller, and the transfer target is the callee.
2631          *
2632          * The problem is that these macros were set with the intention of the original
2633          * caller and callee taking those roles.  A transfer can totally mess things up,
2634          * to be technical.  What sucks even more is that you can't effectively change
2635          * the macros in the dialplan during the call from the transferer to the transfer
2636          * target because the transferee is stuck with whatever role he originally had.
2637          *
2638          * I think the answer here is just to make sure that it is well documented that
2639          * during a transfer, the transferee is the "caller" and the transfer target
2640          * is the "callee."
2641          *
2642          * This means that if party B calls party A, and party B transfers party A to
2643          * party C, then A has switched roles for the call.  Now party A will have the
2644          * caller macro called on his channel instead of the callee macro.
2645          *
2646          * Luckily, the method by which the party B to party C bridge is
2647          * launched above ensures that the transferee is the "chan" on
2648          * the bridge and the transfer target is the "peer," so my idea
2649          * for the roles post-transfer does not require extensive code
2650          * changes.
2651          */
2652
2653         /* Transfer party C connected line to party A */
2654         ast_channel_lock(transferer);
2655         /*
2656          * Due to a limitation regarding when callerID is set on a Local channel,
2657          * we use the transferer's connected line information here.
2658          */
2659         ast_party_connected_line_copy(&connected_line, ast_channel_connected(transferer));
2660         ast_channel_unlock(transferer);
2661         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2662         if (ast_channel_connected_line_sub(newchan, xferchan, &connected_line, 0) &&
2663                 ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
2664                 ast_channel_update_connected_line(xferchan, &connected_line, NULL);
2665         }
2666
2667         /* Transfer party A connected line to party C */
2668         ast_channel_lock(xferchan);
2669         ast_connected_line_copy_from_caller(&connected_line, ast_channel_caller(xferchan));
2670         ast_channel_unlock(xferchan);
2671         connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2672         if (ast_channel_connected_line_sub(xferchan, newchan, &connected_line, 0) &&
2673                 ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
2674                 ast_channel_update_connected_line(newchan, &connected_line, NULL);
2675         }
2676
2677         if (ast_stream_and_wait(newchan, xfer_cfg->xfersound, ""))
2678                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2679         bridge_call_thread_launch(tobj);
2680
2681         ast_party_connected_line_free(&connected_line);
2682         return -1;/* The transferee is masqueraded and the original bridged channels can be hungup. */
2683 }
2684 #endif
2685
2686 /*!
2687  * \internal
2688  * \brief Get the extension for a given builtin feature
2689  *
2690  * \pre expects features_lock to be readlocked
2691  *
2692  * \retval 0 success
2693  * \retval non-zero failiure
2694  */
2695 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name,
2696                 char *buf, size_t len)
2697 {
2698         SCOPED_CHANNELLOCK(lock, chan);
2699
2700         return ast_get_builtin_feature(chan, feature_name, buf, len);
2701 }
2702
2703 static void set_config_flags(struct ast_channel *chan, struct ast_bridge_config *config)
2704 {
2705 /* BUGBUG there is code that checks AST_BRIDGE_IGNORE_SIGS but no code to set it. */
2706 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_0 but no code to set it. */
2707 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_1 but no code to set it. */
2708         ast_clear_flag(config, AST_FLAGS_ALL);
2709
2710         if (ast_test_flag(&config->features_caller, AST_FEATURE_DTMF_MASK)) {
2711                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2712         }
2713         if (ast_test_flag(&config->features_callee, AST_FEATURE_DTMF_MASK)) {
2714                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2715         }
2716
2717         if (!(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2718                 RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
2719
2720                 ast_channel_lock(chan);
2721                 applicationmap = ast_get_chan_applicationmap(chan);
2722                 ast_channel_unlock(chan);
2723
2724                 if (!applicationmap) {
2725                         return;
2726                 }
2727
2728                 /* If an applicationmap exists for this channel at all, then the channel needs the DTMF flag set */
2729                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2730         }
2731 }
2732
2733 #if 0
2734 /*!
2735  * \internal
2736  * \brief Get feature and dial.
2737  *
2738  * \param caller Channel to represent as the calling channel for the dialed channel.
2739  * \param caller_name Original caller channel name.
2740  * \param requestor Channel to say is requesting the dial (usually the caller).
2741  * \param transferee Channel that the dialed channel will be transferred to.
2742  * \param type Channel technology type to dial.
2743  * \param format Codec formats for dialed channel.
2744  * \param addr destination of the call
2745  * \param timeout Time limit for dialed channel to answer in ms. Must be greater than zero.
2746  * \param outstate Status of dialed channel if unsuccessful.
2747  * \param language Language of the caller.
2748  *
2749  * \note
2750  * outstate can be:
2751  * 0, AST_CONTROL_BUSY, AST_CONTROL_CONGESTION,
2752  * AST_CONTROL_ANSWER, or AST_CONTROL_UNHOLD.  If
2753  * AST_CONTROL_UNHOLD then the caller channel cancelled the
2754  * transfer or the dialed channel did not answer before the
2755  * timeout.
2756  *
2757  * \details
2758  * Request channel, set channel variables, initiate call,
2759  * check if they want to disconnect, go into loop, check if timeout has elapsed,
2760  * check if person to be transfered hung up, check for answer break loop,
2761  * set cdr return channel.
2762  *
2763  * \retval Channel Connected channel for transfer.
2764  * \retval NULL on failure to get third party connected.
2765  *
2766  * \note This is similar to __ast_request_and_dial() in channel.c
2767  */
2768 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller,
2769         const char *caller_name, struct ast_channel *requestor,
2770         struct ast_channel *transferee, const char *type, struct ast_format_cap *cap, const char *addr,
2771         int timeout, int *outstate, const char *language)
2772 {
2773         int state = 0;
2774         int cause = 0;
2775         int to;
2776         int caller_hungup;
2777         int transferee_hungup;
2778         struct ast_channel *chan;
2779         struct ast_channel *monitor_chans[3];
2780         struct ast_channel *active_channel;
2781         int res;
2782         int ready = 0;
2783         struct timeval started;
2784         int x, len = 0;
2785         char disconnect_code[AST_FEATURE_MAX_LEN];
2786         char *dialed_code = NULL;
2787         struct ast_format_cap *tmp_cap;
2788         struct ast_format best_audio_fmt;
2789         struct ast_frame *f;
2790         int disconnect_res;
2791         AST_LIST_HEAD_NOLOCK(, ast_frame) deferred_frames;
2792
2793         tmp_cap = ast_format_cap_alloc_nolock();
2794         if (!tmp_cap) {
2795                 if (outstate) {
2796                         *outstate = 0;
2797                 }
2798                 return NULL;
2799         }
2800         ast_best_codec(cap, &best_audio_fmt);
2801         ast_format_cap_add(tmp_cap, &best_audio_fmt);
2802
2803         caller_hungup = ast_check_hangup(caller);
2804
2805         if (!(chan = ast_request(type, tmp_cap, requestor, addr, &cause))) {
2806                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, addr);
2807                 switch (cause) {
2808                 case AST_CAUSE_BUSY:
2809                         state = AST_CONTROL_BUSY;
2810                         break;
2811                 case AST_CAUSE_CONGESTION:
2812                         state = AST_CONTROL_CONGESTION;
2813                         break;
2814                 default:
2815                         state = 0;
2816                         break;
2817                 }
2818                 goto done;
2819         }
2820
2821         ast_channel_language_set(chan, language);
2822         ast_channel_inherit_variables(caller, chan);
2823         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller_name);
2824
2825         ast_channel_lock(chan);
2826         ast_connected_line_copy_from_caller(ast_channel_connected(chan), ast_channel_caller(requestor));
2827         ast_channel_unlock(chan);
2828
2829         if (ast_call(chan, addr, timeout)) {
2830                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, addr);
2831                 switch (ast_channel_hangupcause(chan)) {
2832                 case AST_CAUSE_BUSY:
2833                         state = AST_CONTROL_BUSY;
2834                         break;
2835                 case AST_CAUSE_CONGESTION:
2836                         state = AST_CONTROL_CONGESTION;
2837                         break;
2838                 default:
2839                         state = 0;
2840                         break;
2841                 }
2842                 goto done;
2843         }
2844
2845         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2846         ast_channel_lock(chan);
2847         disconnect_res = ast_get_builtin_feature(chan, "disconnect",
2848                         disconnect_code, sizeof(disconnect_code));
2849         ast_channel_unlock(chan);
2850
2851         if (!disconnect_res) {
2852                 len = strlen(disconnect_code) + 1;
2853                 dialed_code = ast_alloca(len);
2854                 memset(dialed_code, 0, len);
2855         }
2856
2857         x = 0;
2858         started = ast_tvnow();
2859         to = timeout;
2860         AST_LIST_HEAD_INIT_NOLOCK(&deferred_frames);
2861
2862         ast_poll_channel_add(caller, chan);
2863
2864         transferee_hungup = 0;
2865         while (!ast_check_hangup(transferee) && (ast_channel_state(chan) != AST_STATE_UP)) {
2866                 int num_chans = 0;
2867
2868                 monitor_chans[num_chans++] = transferee;
2869                 monitor_chans[num_chans++] = chan;
2870                 if (!caller_hungup) {
2871                         if (ast_check_hangup(caller)) {
2872                                 caller_hungup = 1;
2873
2874 #if defined(ATXFER_NULL_TECH)
2875                                 /* Change caller's name to ensure that it will remain unique. */
2876                                 set_new_chan_name(caller);
2877
2878                                 /*
2879                                  * Get rid of caller's physical technology so it is free for
2880                                  * other calls.
2881                                  */
2882                                 set_kill_chan_tech(caller);
2883 #endif  /* defined(ATXFER_NULL_TECH) */
2884                         } else {
2885                                 /* caller is not hungup so monitor it. */
2886                                 monitor_chans[num_chans++] = caller;
2887                         }
2888                 }
2889
2890                 /* see if the timeout has been violated */
2891                 if (ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2892                         state = AST_CONTROL_UNHOLD;
2893                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout for %s\n", ast_channel_name(chan));
2894                         break; /*doh! timeout*/
2895                 }
2896
2897                 active_channel = ast_waitfor_n(monitor_chans, num_chans, &to);
2898                 if (!active_channel)
2899                         continue;
2900
2901                 f = NULL;
2902                 if (transferee == active_channel) {
2903                         struct ast_frame *dup_f;
2904
2905                         f = ast_read(transferee);
2906                         if (f == NULL) { /*doh! where'd he go?*/
2907                                 transferee_hungup = 1;
2908                                 state = 0;
2909                                 break;
2910                         }
2911                         if (ast_is_deferrable_frame(f)) {
2912                                 dup_f = ast_frisolate(f);
2913                                 if (dup_f) {
2914                                         if (dup_f == f) {
2915                                                 f = NULL;
2916                                         }
2917                                         AST_LIST_INSERT_HEAD(&deferred_frames, dup_f, frame_list);
2918                                 }
2919                         }
2920                 } else if (chan == active_channel) {
2921                         if (!ast_strlen_zero(ast_channel_call_forward(chan))) {
2922                                 state = 0;
2923                                 ast_autoservice_start(transferee);
2924                                 chan = ast_call_forward(caller, chan, NULL, tmp_cap, NULL, &state);
2925                                 ast_autoservice_stop(transferee);
2926                                 if (!chan) {
2927                                         break;
2928                                 }
2929                                 continue;
2930                         }
2931                         f = ast_read(chan);
2932                         if (f == NULL) { /*doh! where'd he go?*/
2933                                 switch (ast_channel_hangupcause(chan)) {
2934                                 case AST_CAUSE_BUSY:
2935                                         state = AST_CONTROL_BUSY;
2936                                         break;
2937                                 case AST_CAUSE_CONGESTION:
2938                                         state = AST_CONTROL_CONGESTION;
2939                                         break;
2940                                 default:
2941                                         state = 0;
2942                                         break;
2943                                 }
2944                                 break;
2945                         }
2946
2947                         if (f->frametype == AST_FRAME_CONTROL) {
2948                                 if (f->subclass.integer == AST_CONTROL_RINGING) {
2949                                         ast_verb(3, "%s is ringing\n", ast_channel_name(chan));
2950                                         ast_indicate(caller, AST_CONTROL_RINGING);
2951                                 } else if (f->subclass.integer == AST_CONTROL_BUSY) {
2952                                         state = f->subclass.integer;
2953                                         ast_verb(3, "%s is busy\n", ast_channel_name(chan));
2954                                         ast_indicate(caller, AST_CONTROL_BUSY);
2955                                         ast_frfree(f);
2956                                         break;
2957                                 } else if (f->subclass.integer == AST_CONTROL_INCOMPLETE) {
2958                                         ast_verb(3, "%s dialed incomplete extension %s; ignoring\n", ast_channel_name(chan), ast_channel_exten(chan));
2959                                 } else if (f->subclass.integer == AST_CONTROL_CONGESTION) {
2960                                         state = f->subclass.integer;
2961                                         ast_verb(3, "%s is congested\n", ast_channel_name(chan));
2962                                         ast_indicate(caller, AST_CONTROL_CONGESTION);
2963                                         ast_frfree(f);
2964                                         break;
2965                                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
2966                                         /* This is what we are hoping for */
2967                                         state = f->subclass.integer;
2968                                         ast_frfree(f);
2969                                         ready=1;
2970                                         break;
2971                                 } else if (f->subclass.integer == AST_CONTROL_PVT_CAUSE_CODE) {
2972                                         ast_indicate_data(caller, AST_CONTROL_PVT_CAUSE_CODE, f->data.ptr, f->datalen);
2973                                 } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
2974                                         if (caller_hungup) {
2975                                                 struct ast_party_connected_line connected;
2976
2977                                                 /* Just save it for the transfer. */
2978                                                 ast_party_connected_line_set_init(&connected, ast_channel_connected(caller));
2979                                                 res = ast_connected_line_parse_data(f->data.ptr, f->datalen,
2980                                                         &connected);
2981                                                 if (!res) {
2982                                                         ast_channel_set_connected_line(caller, &connected, NULL);
2983                                                 }
2984                                                 ast_party_connected_line_free(&connected);
2985                                         } else {
2986                                                 ast_autoservice_start(transferee);
2987                                                 if (ast_channel_connected_line_sub(chan, caller, f, 1) &&
2988                                                         ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
2989                                                         ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE,
2990                                                                 f->data.ptr, f->datalen);
2991                                                 }
2992                                                 ast_autoservice_stop(transferee);
2993                                         }
2994                                 } else if (f->subclass.integer == AST_CONTROL_REDIRECTING) {
2995                                         if (!caller_hungup) {
2996                                                 ast_autoservice_start(transferee);
2997                                                 if (ast_channel_redirecting_sub(chan, caller, f, 1) &&
2998                                                         ast_channel_redirecting_macro(chan, caller, f, 1, 1)) {
2999                                                         ast_indicate_data(caller, AST_CONTROL_REDIRECTING,
3000                                                                 f->data.ptr, f->datalen);
3001                                                 }
3002                                                 ast_autoservice_stop(transferee);
3003                                         }
3004                                 } else if (f->subclass.integer != -1
3005                                         && f->subclass.integer != AST_CONTROL_PROGRESS
3006                                         && f->subclass.integer != AST_CONTROL_PROCEEDING) {
3007                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
3008                                 }
3009                                 /* else who cares */
3010                         } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3011                                 ast_write(caller, f);
3012                         }
3013                 } else if (caller == active_channel) {
3014                         f = ast_read(caller);
3015                         if (f) {
3016                                 if (f->frametype == AST_FRAME_DTMF && dialed_code) {
3017                                         dialed_code[x++] = f->subclass.integer;
3018                                         dialed_code[x] = '\0';
3019                                         if (strlen(dialed_code) == len) {
3020                                                 x = 0;
3021                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
3022                                                 x = 0;
3023                                                 dialed_code[x] = '\0';
3024                                         }
3025                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
3026                                                 /* Caller Canceled the call */
3027                                                 state = AST_CONTROL_UNHOLD;
3028                                                 ast_frfree(f);
3029                                                 break;
3030                                         }
3031                                 } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
3032                                         ast_write(chan, f);
3033                                 }
3034                         }
3035                 }
3036                 if (f)
3037                         ast_frfree(f);
3038         } /* end while */
3039
3040         ast_poll_channel_del(caller, chan);
3041
3042         /*
3043          * We need to free all the deferred frames, but we only need to
3044          * queue the deferred frames if no hangup was received.
3045          */
3046         ast_channel_lock(transferee);
3047         transferee_hungup = (transferee_hungup || ast_check_hangup(transferee));
3048         while ((f = AST_LIST_REMOVE_HEAD(&deferred_frames, frame_list))) {
3049                 if (!transferee_hungup) {
3050                         ast_queue_frame_head(transferee, f);
3051                 }
3052                 ast_frfree(f);
3053         }
3054         ast_channel_unlock(transferee);
3055
3056 done:
3057         ast_indicate(caller, -1);
3058         if (chan && (ready || ast_channel_state(chan) == AST_STATE_UP)) {
3059                 state = AST_CONTROL_ANSWER;
3060         } else if (chan) {
3061                 ast_hangup(chan);
3062                 chan = NULL;
3063         }
3064
3065         tmp_cap = ast_format_cap_destroy(tmp_cap);
3066
3067         if (outstate)
3068                 *outstate = state;
3069
3070         return chan;
3071 }
3072 #endif
3073
3074 void ast_channel_log(char *title, struct ast_channel *chan);
3075
3076 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
3077 {
3078         ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long) chan);
3079         ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
3080                 ast_channel_name(chan), ast_channel_appl(chan), ast_channel_data(chan),
3081                 ast_channel_context(chan), ast_channel_exten(chan), ast_channel_priority(chan));
3082         ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
3083                 ast_channel_accountcode(chan), ast_channel_dialcontext(chan), ast_channel_amaflags(chan),
3084                 ast_channel_macrocontext(chan), ast_channel_macroexten(chan), ast_channel_macropriority(chan));
3085         ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; uniqueID: %s; linkedID:%s\n",
3086                 ast_channel_masq(chan), ast_channel_masqr(chan),
3087                 ast_channel_uniqueid(chan), ast_channel_linkedid(chan));
3088         if (ast_channel_masqr(chan)) {
3089                 ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
3090                         ast_channel_name(ast_channel_masqr(chan)), ast_channel_cdr(ast_channel_masqr(chan)));
3091         }
3092
3093         ast_log(LOG_NOTICE, "===== done ====\n");
3094 }
3095
3096 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
3097 {
3098         const char *feature;
3099
3100         if (ast_strlen_zero(features)) {
3101                 return;
3102         }
3103
3104         for (feature = features; *feature; feature++) {
3105                 struct ast_flags *party;
3106
3107                 if (isupper(*feature)) {
3108                         party = &config->features_caller;
3109                 } else {
3110                         party = &config->features_callee;
3111                 }
3112
3113                 switch (tolower(*feature)) {
3114                 case 't' :
3115                         ast_set_flag(party, AST_FEATURE_REDIRECT);
3116                         break;
3117                 case 'k' :
3118                         ast_set_flag(party, AST_FEATURE_PARKCALL);
3119                         break;
3120                 case 'h' :
3121                         ast_set_flag(party, AST_FEATURE_DISCONNECT);
3122                         break;
3123                 case 'w' :
3124                         ast_set_flag(party, AST_FEATURE_AUTOMON);
3125                         break;
3126                 case 'x' :
3127                         ast_set_flag(party, AST_FEATURE_AUTOMIXMON);
3128                         break;
3129                 default :
3130                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
3131                         break;
3132                 }
3133         }
3134 }
3135
3136 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
3137 {
3138         if (add_features_datastore(caller, &config->features_caller, &config->features_callee)) {
3139                 /*
3140                  * If we don't return here, then when we do a builtin_atxfer we
3141                  * will copy the disconnect flags over from the atxfer to the
3142                  * callee (Party C).
3143                  */
3144                 return;
3145         }
3146
3147         add_features_datastore(callee, &config->features_callee, &config->features_caller);
3148 }
3149
3150 static void clear_dialed_interfaces(struct ast_channel *chan)
3151 {
3152         struct ast_datastore *di_datastore;
3153
3154         ast_channel_lock(chan);
3155         if ((di_datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL))) {
3156                 if (option_debug) {
3157                         ast_log(LOG_DEBUG, "Removing dialed interfaces datastore on %s since we're bridging\n", ast_channel_name(chan));
3158                 }
3159                 if (!ast_channel_datastore_remove(chan, di_datastore)) {
3160                         ast_datastore_free(di_datastore);
3161                 }
3162         }
3163         ast_channel_unlock(chan);
3164 }
3165
3166 void ast_bridge_end_dtmf(struct ast_channel *chan, char digit, struct timeval start, const char *why)
3167 {
3168         int dead;
3169         long duration;
3170
3171         ast_channel_lock(chan);
3172         dead = ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
3173                 || (ast_channel_softhangup_internal_flag(chan)
3174                         & ~(AST_SOFTHANGUP_ASYNCGOTO | AST_SOFTHANGUP_UNBRIDGE));
3175         ast_channel_unlock(chan);
3176         if (dead) {
3177                 /* Channel is a zombie or a real hangup. */
3178                 return;
3179         }
3180
3181         duration = ast_tvdiff_ms(ast_tvnow(), start);
3182         ast_senddigit_end(chan, digit, duration);
3183         ast_log(LOG_DTMF, "DTMF end '%c' simulated on %s due to %s, duration %ld ms\n",
3184                 digit, ast_channel_name(chan), why, duration);
3185 }
3186
3187 /*!
3188  * \internal
3189  * \brief Setup bridge builtin features.
3190  * \since 12.0.0
3191  *
3192  * \param features Bridge features to setup.
3193  * \param chan Get features from this channel.
3194  *
3195  * \retval 0 on success.
3196  * \retval -1 on error.
3197  */
3198 static int setup_bridge_features_builtin(struct ast_bridge_features *features, struct ast_channel *chan)
3199 {
3200         struct ast_flags *flags;
3201         char dtmf[AST_FEATURE_MAX_LEN];
3202         int res;
3203
3204         ast_channel_lock(chan);
3205         flags = ast_bridge_features_ds_get(chan);
3206         ast_channel_unlock(chan);
3207         if (!flags) {
3208                 return 0;
3209         }
3210
3211         res = 0;
3212         if (ast_test_flag(flags, AST_FEATURE_REDIRECT)) {
3213                 /* Add atxfer and blind transfer. */
3214                 if (!builtin_feature_get_exten(chan, "blindxfer", dtmf, sizeof(dtmf))
3215                                 && !ast_strlen_zero(dtmf)) {
3216 /* BUGBUG need to supply a blind transfer structure and destructor to use other than defaults */
3217                         res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_BLINDTRANSFER, dtmf,
3218                                         NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3219                 }
3220                 if (!builtin_feature_get_exten(chan, "atxfer", dtmf, sizeof(dtmf)) &&
3221                                 !ast_strlen_zero(dtmf)) {
3222 /* BUGBUG need to supply an attended transfer structure and destructor to use other than defaults */
3223                         res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER, dtmf,
3224                                         NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3225                 }
3226         }
3227         if (ast_test_flag(flags, AST_FEATURE_DISCONNECT) &&
3228                         !builtin_feature_get_exten(chan, "disconnect", dtmf, sizeof(dtmf)) &&
3229                         !ast_strlen_zero(dtmf)) {
3230                 res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_HANGUP, dtmf,
3231                                 NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3232         }
3233         if (ast_test_flag(flags, AST_FEATURE_PARKCALL) &&
3234                         !builtin_feature_get_exten(chan, "parkcall", dtmf, sizeof(dtmf)) &&
3235                         !ast_strlen_zero(dtmf)) {
3236                 res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_PARKCALL, dtmf,
3237                                 NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3238         }
3239         if (ast_test_flag(flags, AST_FEATURE_AUTOMON) &&
3240                         !builtin_feature_get_exten(chan, "automon", dtmf, sizeof(dtmf)) &&
3241                         !ast_strlen_zero(dtmf)) {
3242                 res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_AUTOMON, dtmf,
3243                                 NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3244         }
3245         if (ast_test_flag(flags, AST_FEATURE_AUTOMIXMON) &&
3246                         !builtin_feature_get_exten(chan, "automixmon", dtmf, sizeof(dtmf)) &&
3247                         !ast_strlen_zero(dtmf)) {
3248                 res |= ast_bridge_features_enable(features, AST_BRIDGE_BUILTIN_AUTOMIXMON, dtmf,
3249                                 NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3250         }
3251
3252 #if 0   /* BUGBUG don't report errors untill all of the builtin features are supported. */
3253         return res ? -1 : 0;
3254 #else
3255         return 0;
3256 #endif
3257 }
3258
3259 struct dynamic_dtmf_hook_run {
3260         /*! Offset into app_name[] where the channel name that activated the hook starts. */
3261         int activated_offset;
3262         /*! Offset into app_name[] where the dynamic feature name starts. */
3263         int feature_offset;
3264         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
3265         int moh_offset;
3266         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
3267         int app_args_offset;
3268         /*! Application name to run. */
3269         char app_name[0];
3270 };
3271
3272 static void dynamic_dtmf_hook_callback(struct ast_bridge_channel *bridge_channel,
3273         const void *payload, size_t payload_size)
3274 {
3275         struct ast_channel *chan = bridge_channel->chan;
3276         const struct dynamic_dtmf_hook_run *run_data = payload;
3277
3278         pbx_builtin_setvar_helper(chan, "DYNAMIC_FEATURENAME",
3279                 &run_data->app_name[run_data->feature_offset]);
3280         pbx_builtin_setvar_helper(chan, "DYNAMIC_WHO_ACTIVATED",
3281                 &run_data->app_name[run_data->activated_offset]);
3282
3283         ast_bridge_channel_run_app(bridge_channel, run_data->app_name,
3284                 run_data->app_args_offset ? &run_data->app_name[run_data->app_args_offset] : NULL,
3285                 run_data->moh_offset ? &run_data->app_name[run_data->moh_offset] : NULL);
3286 }
3287
3288 static int dynamic_dtmf_hook_run_callback(struct ast_bridge_channel *bridge_channel,
3289         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
3290 {
3291         callback(bridge_channel, payload, payload_size);
3292         return 0;
3293 }
3294
3295 struct dynamic_dtmf_hook_data {
3296         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
3297         unsigned int flags;
3298         /*! Offset into app_name[] where the dynamic feature name starts. */
3299         int feature_offset;
3300         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
3301         int moh_offset;
3302         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
3303         int app_args_offset;
3304         /*! Application name to run. */
3305         char app_name[0];
3306 };
3307
3308 /*!
3309  * \internal
3310  * \brief Activated dynamic DTMF feature hook.
3311  * \since 12.0.0
3312  *
3313  * \param bridge The bridge that the channel is part of
3314  * \param bridge_channel Channel executing the feature
3315  * \param hook_pvt Private data passed in when the hook was created
3316  *
3317  * \retval 0 Keep the callback hook.
3318  * \retval -1 Remove the callback hook.
3319  */
3320 static int dynamic_dtmf_hook_trip(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
3321 {
3322         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
3323         int (*run_it)(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size);
3324         struct dynamic_dtmf_hook_run *run_data;
3325         const char *activated_name;
3326         size_t len_name;
3327         size_t len_args;
3328         size_t len_moh;
3329         size_t len_feature;
3330         size_t len_activated;
3331         size_t len_data;
3332
3333         /* Determine lengths of things. */
3334         len_name = strlen(pvt->app_name) + 1;
3335         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
3336         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
3337         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
3338         ast_channel_lock(bridge_channel->chan);
3339         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
3340         ast_channel_unlock(bridge_channel->chan);
3341         len_activated = strlen(activated_name) + 1;
3342         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
3343
3344         /* Fill in dynamic feature run hook data. */
3345         run_data = ast_alloca(len_data);
3346         run_data->app_args_offset = len_args ? len_name : 0;
3347         run_data->moh_offset = len_moh ? len_name + len_args : 0;
3348         run_data->feature_offset = len_name + len_args + len_moh;
3349         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
3350         strcpy(run_data->app_name, pvt->app_name);/* Safe */
3351         if (len_args) {
3352                 strcpy(&run_data->app_name[run_data->app_args_offset],
3353                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
3354         }
3355         if (len_moh) {
3356                 strcpy(&run_data->app_name[run_data->moh_offset],
3357                         &pvt->app_name[pvt->moh_offset]);/* Safe */
3358         }
3359         strcpy(&run_data->app_name[run_data->feature_offset],
3360                 &pvt->app_name[pvt->feature_offset]);/* Safe */
3361         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
3362
3363         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
3364                 run_it = ast_bridge_channel_write_callback;
3365         } else {
3366                 run_it = dynamic_dtmf_hook_run_callback;
3367         }
3368         run_it(bridge_channel, dynamic_dtmf_hook_callback, run_data, len_data);
3369         return 0;
3370 }
3371
3372 /*!
3373  * \internal
3374  * \brief Add a dynamic DTMF feature hook to the bridge features.
3375  * \since 12.0.0
3376  *
3377  * \param features Bridge features to setup.
3378  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
3379  * \param dtmf DTMF trigger sequence.
3380  * \param feature_name Name of the dynamic feature.
3381  * \param app_name Dialplan application name to run.
3382  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
3383  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
3384  *
3385  * \retval 0 on success.
3386  * \retval -1 on error.
3387  */
3388 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)
3389 {
3390         struct dynamic_dtmf_hook_data *hook_data;
3391         size_t len_name = strlen(app_name) + 1;
3392         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
3393         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
3394         size_t len_feature = strlen(feature_name) + 1;
3395         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
3396         int res;
3397
3398         /* Fill in application run hook data. */
3399         hook_data = ast_malloc(len_data);
3400         if (!hook_data) {
3401                 return -1;
3402         }
3403         hook_data->flags = flags;
3404         hook_data->app_args_offset = len_args ? len_name : 0;
3405         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
3406         hook_data->feature_offset = len_name + len_args + len_moh;
3407         strcpy(hook_data->app_name, app_name);/* Safe */
3408         if (len_args) {
3409                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
3410         }
3411         if (len_moh) {
3412                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
3413         }
3414         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
3415
3416         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
3417                 ast_free_ptr, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
3418         if (res) {
3419                 ast_free(hook_data);
3420         }
3421         return res;
3422 }
3423
3424 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
3425 {
3426         struct ast_applicationmap_item *item = obj;
3427         struct ast_bridge_features *features = arg;
3428         int *res = data;
3429
3430         *res |= dynamic_dtmf_hook_add(features,
3431                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
3432                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
3433
3434         return 0;
3435 }
3436
3437 /*!
3438  * \internal
3439  * \brief Setup bridge dynamic features.
3440  * \since 12.0.0
3441  *
3442  * \param features Bridge features to setup.
3443  * \param chan Get features from this channel.
3444  *
3445  * \retval 0 on success.
3446  * \retval -1 on error.
3447  */
3448 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
3449 {
3450         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
3451         int res = 0;
3452
3453         ast_channel_lock(chan);
3454         applicationmap = ast_get_chan_applicationmap(chan);
3455         ast_channel_unlock(chan);
3456         if (!applicationmap) {
3457                 return 0;
3458         }
3459
3460         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
3461
3462         return res;
3463 }
3464
3465 /* BUGBUG this really should be made a private function of bridging_basic.c after struct ast_call_feature is made an ao2 object. */
3466 int ast_bridge_channel_setup_features(struct ast_bridge_channel *bridge_channel)
3467 {
3468         int res = 0;
3469
3470         /* Always pass through any DTMF digits. */
3471         bridge_channel->features->dtmf_passthrough = 1;
3472
3473         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
3474         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
3475
3476         return res;
3477 }
3478
3479 static void bridge_config_set_limits_warning_values(struct ast_bridge_config *config, struct ast_bridge_features_limits *limits)
3480 {
3481         if (config->end_sound) {
3482                 ast_string_field_set(limits, duration_sound, config->end_sound);
3483         }
3484
3485         if (config->warning_sound) {
3486                 ast_string_field_set(limits, warning_sound, config->warning_sound);
3487         }
3488
3489         if (config->start_sound) {
3490                 ast_string_field_set(limits, connect_sound, config->start_sound);
3491         }
3492
3493         limits->frequency = config->warning_freq;
3494         limits->warning = config->play_warning;
3495 }
3496
3497 /*!
3498  * \internal brief Setup limit hook structures on calls that need limits
3499  *
3500  * \param config ast_bridge_config which provides the limit data
3501  * \param caller_limits pointer to an ast_bridge_features_limits struct which will store the caller side limits
3502  * \param callee_limits pointer to an ast_bridge_features_limits struct which will store the callee side limits
3503  */
3504 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)
3505 {
3506         if (ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING)) {
3507                 bridge_config_set_limits_warning_values(config, caller_limits);
3508         }
3509
3510         if (ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING)) {
3511                 bridge_config_set_limits_warning_values(config, callee_limits);
3512         }
3513
3514         caller_limits->duration = config->timelimit;
3515         callee_limits->duration = config->timelimit;
3516 }
3517
3518 /*!
3519  * \internal
3520  * \brief Check if Monitor needs to be started on a channel.
3521  * \since 12.0.0
3522  *
3523  * \param chan The bridge considers this channel the caller.
3524  * \param peer The bridge considers this channel the callee.
3525  *
3526  * \return Nothing
3527  */
3528 static void bridge_check_monitor(struct ast_channel *chan, struct ast_channel *peer)
3529 {
3530         const char *value;
3531         const char *monitor_args = NULL;
3532         struct ast_channel *monitor_chan = NULL;
3533
3534         ast_channel_lock(chan);
3535         value = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR");
3536         if (!ast_strlen_zero(value)) {
3537                 monitor_args = ast_strdupa(value);
3538                 monitor_chan = chan;
3539         }
3540         ast_channel_unlock(chan);
3541         if (!monitor_chan) {
3542                 ast_channel_lock(peer);
3543                 value = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR");
3544                 if (!ast_strlen_zero(value)) {