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