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