417f18c66edfeba874041710552d5fb2b8a35980
[asterisk/asterisk.git] / main / features.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  * Copyright (C) 2012, Russell Bryant
6  *
7  * Mark Spencer <markster@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Routines implementing call features as call pickup, parking and transfer
23  *
24  * \author Mark Spencer <markster@digium.com>
25  */
26
27 /*! \li \ref features.c uses the configuration file \ref features.conf
28  * \addtogroup configuration_file Configuration Files
29  */
30
31 /*!
32  * \page features.conf features.conf
33  * \verbinclude features.conf.sample
34  */
35
36 /*** MODULEINFO
37         <support_level>core</support_level>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include "asterisk/_private.h"
45
46 #include <pthread.h>
47 #include <signal.h>
48 #include <sys/time.h>
49 #include <sys/signal.h>
50 #include <netinet/in.h>
51
52 #include "asterisk/lock.h"
53 #include "asterisk/file.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/module.h"
58 #include "asterisk/translate.h"
59 #include "asterisk/app.h"
60 #include "asterisk/say.h"
61 #include "asterisk/features.h"
62 #include "asterisk/musiconhold.h"
63 #include "asterisk/config.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/manager.h"
66 #include "asterisk/utils.h"
67 #include "asterisk/adsi.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/monitor.h"
70 #include "asterisk/audiohook.h"
71 #include "asterisk/global_datastores.h"
72 #include "asterisk/astobj2.h"
73 #include "asterisk/test.h"
74 #include "asterisk/bridge.h"
75 #include "asterisk/bridge_basic.h"
76 #include "asterisk/bridge_after.h"
77 #include "asterisk/stasis.h"
78 #include "asterisk/stasis_channels.h"
79 #include "asterisk/features_config.h"
80
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 static const struct ast_datastore_info channel_app_data_datastore = {
779         .type = "Channel appdata datastore",
780         .destroy = ast_free_ptr,
781 };
782
783 /*!
784  * \brief Announce call parking by ADSI
785  * \param chan .
786  * \param parkingexten .
787  * Create message to show for ADSI, display message.
788  * \retval 0 on success.
789  * \retval -1 on failure.
790  */
791 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
792 {
793         int res;
794         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
795         char tmp[256];
796         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
797
798         snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
799         message[0] = tmp;
800         res = ast_adsi_load_session(chan, NULL, 0, 1);
801         if (res == -1)
802                 return res;
803         return ast_adsi_print(chan, message, justify, 1);
804 }
805
806 /*!
807  * \brief Find parking lot name from channel
808  * \note Channel needs to be locked while the returned string is in use.
809  */
810 static const char *findparkinglotname(struct ast_channel *chan)
811 {
812         const char *name;
813
814         /* The channel variable overrides everything */
815         name = pbx_builtin_getvar_helper(chan, "PARKINGLOT");
816         if (!name && !ast_strlen_zero(ast_channel_parkinglot(chan))) {
817                 /* Use the channel's parking lot. */
818                 name = ast_channel_parkinglot(chan);
819         }
820         return name;
821 }
822
823 /*! \brief Notify metermaids that we've changed an extension */
824 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
825 {
826         ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'",
827                 exten, context, ast_devstate2str(state));
828
829         ast_devstate_changed(state, AST_DEVSTATE_CACHABLE, "park:%s@%s", exten, context);
830 }
831
832 /*! \brief metermaids callback from devicestate.c */
833 static enum ast_device_state metermaidstate(const char *data)
834 {
835         char *context;
836         char *exten;
837
838         context = ast_strdupa(data);
839
840         exten = strsep(&context, "@");
841         if (!context)
842                 return AST_DEVICE_INVALID;
843
844         ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
845
846         if (!ast_exists_extension(NULL, context, exten, 1, NULL))
847                 return AST_DEVICE_NOT_INUSE;
848
849         return AST_DEVICE_INUSE;
850 }
851
852 /*! Options to pass to park_call_full */
853 enum ast_park_call_options {
854         /*! Provide ringing to the parked caller instead of music on hold */
855         AST_PARK_OPT_RINGING =   (1 << 0),
856         /*! Randomly choose a parking spot for the caller instead of choosing
857          *  the first one that is available. */
858         AST_PARK_OPT_RANDOMIZE = (1 << 1),
859         /*! Do not announce the parking number */
860         AST_PARK_OPT_SILENCE = (1 << 2),
861 };
862
863 /*! Optional additional parking options when parking a call. */
864 struct ast_park_call_args {
865         /*! How long to wait in the parking lot before the call gets sent back
866          *  to the specified return extension (or a best guess at where it came
867          *  from if not explicitly specified). */
868         int timeout;
869         /*! An output parameter to store the parking space where the parked caller
870          *  was placed. */
871         int *extout;
872         const char *orig_chan_name;
873         const char *return_con;
874         const char *return_ext;
875         int return_pri;
876         uint32_t flags;
877         /*! Parked user that has already obtained a parking space */
878         struct parkeduser *pu;
879         /*! \brief Parkinglot to be parked in */
880         struct ast_parkinglot *parkinglot;
881 };
882
883 /*!
884  * \internal
885  * \brief Create a dynamic parking lot.
886  *
887  * \param name Dynamic parking lot name to create.
888  * \param chan Channel to get dynamic parking lot parameters.
889  *
890  * \retval parkinglot on success.
891  * \retval NULL on error.
892  */
893 static struct ast_parkinglot *create_dynamic_parkinglot(const char *name, struct ast_channel *chan)
894 {
895         const char *dyn_context;
896         const char *dyn_exten;
897         const char *dyn_range;
898         const char *template_name;
899         struct ast_parkinglot *template_parkinglot = NULL;
900         struct ast_parkinglot *parkinglot;
901         int dyn_start;
902         int dyn_end;
903
904         ast_channel_lock(chan);
905         template_name = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
906         dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
907         dyn_exten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNEXTEN"), ""));
908         dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
909         ast_channel_unlock(chan);
910
911         if (!ast_strlen_zero(template_name)) {
912                 template_parkinglot = find_parkinglot(template_name);
913                 if (!template_parkinglot) {
914                         ast_debug(1, "PARKINGDYNAMIC lot %s does not exist.\n",
915                                 template_name);
916                 } else if (template_parkinglot->cfg.is_invalid) {
917                         ast_debug(1, "PARKINGDYNAMIC lot %s has invalid config.\n",
918                                 template_name);
919                         parkinglot_unref(template_parkinglot);
920                         template_parkinglot = NULL;
921                 }
922         }
923         if (!template_parkinglot) {
924                 template_parkinglot = parkinglot_addref(default_parkinglot);
925                 ast_debug(1, "Using default parking lot for template\n");
926         }
927
928         parkinglot = copy_parkinglot(name, template_parkinglot);
929         if (!parkinglot) {
930                 ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
931         } else {
932                 /* Configure the dynamic parking lot. */
933                 if (!ast_strlen_zero(dyn_context)) {
934                         ast_copy_string(parkinglot->cfg.parking_con, dyn_context,
935                                 sizeof(parkinglot->cfg.parking_con));
936                 }
937                 if (!ast_strlen_zero(dyn_exten)) {
938                         ast_copy_string(parkinglot->cfg.parkext, dyn_exten,
939                                 sizeof(parkinglot->cfg.parkext));
940                 }
941                 if (!ast_strlen_zero(dyn_range)) {
942                         if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
943                                 ast_log(LOG_WARNING,
944                                         "Format for parking positions is a-b, where a and b are numbers\n");
945                         } else if (dyn_end < dyn_start || dyn_start <= 0 || dyn_end <= 0) {
946                                 ast_log(LOG_WARNING,
947                                         "Format for parking positions is a-b, where a <= b\n");
948                         } else {
949                                 parkinglot->cfg.parking_start = dyn_start;
950                                 parkinglot->cfg.parking_stop = dyn_end;
951                         }
952                 }
953
954                 /*
955                  * Sanity check for dynamic parking lot configuration.
956                  *
957                  * XXX It may be desirable to instead check if the dynamic
958                  * parking lot overlaps any existing lots like what is done for
959                  * a reload.
960                  */
961                 if (!strcmp(parkinglot->cfg.parking_con, template_parkinglot->cfg.parking_con)) {
962                         if (!strcmp(parkinglot->cfg.parkext, template_parkinglot->cfg.parkext)
963                                 && parkinglot->cfg.parkext_exclusive) {
964                                 ast_log(LOG_WARNING,
965                                         "Parking lot '%s' conflicts with template parking lot '%s'!\n"
966                                         "Change either PARKINGDYNCONTEXT or PARKINGDYNEXTEN.\n",
967                                         parkinglot->name, template_parkinglot->name);
968                         }
969                         if ((template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_start
970                                         && parkinglot->cfg.parking_start <= template_parkinglot->cfg.parking_stop)
971                                 || (template_parkinglot->cfg.parking_start <= parkinglot->cfg.parking_stop
972                                         && parkinglot->cfg.parking_stop <= template_parkinglot->cfg.parking_stop)
973                                 || (parkinglot->cfg.parking_start < template_parkinglot->cfg.parking_start
974                                         && template_parkinglot->cfg.parking_stop < parkinglot->cfg.parking_stop)) {
975                                 ast_log(LOG_WARNING,
976                                         "Parking lot '%s' parking spaces overlap template parking lot '%s'!\n"
977                                         "Change PARKINGDYNPOS.\n",
978                                         parkinglot->name, template_parkinglot->name);
979                         }
980                 }
981
982                 parkinglot_activate(parkinglot);
983                 ao2_link(parkinglots, parkinglot);
984         }
985         parkinglot_unref(template_parkinglot);
986
987         return parkinglot;
988 }
989
990 /*!
991  * \internal
992  * \brief Abort parking a call that has not completed parking yet.
993  *
994  * \param pu Parked user item to clean up.
995  *
996  * \note The parking lot parkings list is locked on entry.
997  *
998  * \return Nothing
999  */
1000 static void park_space_abort(struct parkeduser *pu)
1001 {
1002         struct ast_parkinglot *parkinglot;
1003
1004         parkinglot = pu->parkinglot;
1005
1006         /* Put back the parking space just allocated. */
1007         --parkinglot->next_parking_space;
1008
1009         AST_LIST_REMOVE(&parkinglot->parkings, pu, list);
1010
1011         AST_LIST_UNLOCK(&parkinglot->parkings);
1012         parkinglot_unref(parkinglot);
1013         ast_free(pu);
1014 }
1015
1016 /*!
1017  * \internal
1018  * \brief Reserve a parking space in a parking lot for a call being parked.
1019  *
1020  * \param park_me Channel being parked.
1021  * \param parker Channel parking the call.
1022  * \param args Optional additional parking options when parking a call.
1023  *
1024  * \return Parked call descriptor or NULL if failed.
1025  * \note The parking lot list is locked if successful.
1026  */
1027 static struct parkeduser *park_space_reserve(struct ast_channel *park_me, struct ast_channel *parker, struct ast_park_call_args *args)
1028 {
1029         struct parkeduser *pu;
1030         int i;
1031         int parking_space = -1;
1032         const char *parkinglotname;
1033         const char *parkingexten;
1034         struct parkeduser *cur;
1035         struct ast_parkinglot *parkinglot = NULL;
1036
1037         if (args->parkinglot) {
1038                 parkinglot = parkinglot_addref(args->parkinglot);
1039                 parkinglotname = parkinglot->name;
1040         } else {
1041                 if (parker) {
1042                         parkinglotname = findparkinglotname(parker);
1043                 } else { /* parker was NULL, check park_me (ParkAndAnnounce / res_agi) */
1044                         parkinglotname = findparkinglotname(park_me);
1045                 }
1046                 if (!ast_strlen_zero(parkinglotname)) {
1047                         parkinglot = find_parkinglot(parkinglotname);
1048                 } else {
1049                         /* Parking lot is not specified, so use the default parking lot. */
1050                         ast_debug(4, "This could be an indication channel driver needs updating, using default lot.\n");
1051                         parkinglot = parkinglot_addref(default_parkinglot);
1052                 }
1053         }
1054
1055         /* Dynamically create parkinglot */
1056         if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
1057                 parkinglot = create_dynamic_parkinglot(parkinglotname, park_me);
1058         }
1059
1060         if (!parkinglot) {
1061                 ast_log(LOG_WARNING, "Parking lot not available to park %s.\n", ast_channel_name(park_me));
1062                 return NULL;
1063         }
1064
1065         ast_debug(1, "Parking lot: %s\n", parkinglot->name);
1066         if (parkinglot->disabled || parkinglot->cfg.is_invalid) {
1067                 ast_log(LOG_WARNING, "Parking lot %s is not in a useable state.\n",
1068                         parkinglot->name);
1069                 parkinglot_unref(parkinglot);
1070                 return NULL;
1071         }
1072
1073         /* Allocate memory for parking data */
1074         if (!(pu = ast_calloc(1, sizeof(*pu)))) {
1075                 parkinglot_unref(parkinglot);
1076                 return NULL;
1077         }
1078
1079         /* Lock parking list */
1080         AST_LIST_LOCK(&parkinglot->parkings);
1081
1082         /* Check for channel variable PARKINGEXTEN */
1083         parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(park_me, "PARKINGEXTEN"), ""));
1084         if (!ast_strlen_zero(parkingexten)) {
1085                 /*!
1086                  * \note The API forces us to specify a numeric parking slot, even
1087                  * though the architecture would tend to support non-numeric extensions
1088                  * (as are possible with SIP, for example).  Hence, we enforce that
1089                  * limitation here.  If extout was not numeric, we could permit
1090                  * arbitrary non-numeric extensions.
1091                  */
1092                 if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space <= 0) {
1093                         ast_log(LOG_WARNING, "PARKINGEXTEN='%s' is not a valid parking space.\n",
1094                                 parkingexten);
1095                         AST_LIST_UNLOCK(&parkinglot->parkings);
1096                         parkinglot_unref(parkinglot);
1097                         ast_free(pu);
1098                         return NULL;
1099                 }
1100
1101                 if (parking_space < parkinglot->cfg.parking_start
1102                         || parkinglot->cfg.parking_stop < parking_space) {
1103                         /*
1104                          * Cannot allow park because parking lots are not setup for
1105                          * spaces outside of the lot.  (Things like dialplan hints don't
1106                          * exist for outside lot space.)
1107                          */
1108                         ast_log(LOG_WARNING, "PARKINGEXTEN=%d is not in %s (%d-%d).\n",
1109                                 parking_space, parkinglot->name, parkinglot->cfg.parking_start,
1110                                 parkinglot->cfg.parking_stop);
1111                         AST_LIST_UNLOCK(&parkinglot->parkings);
1112                         parkinglot_unref(parkinglot);
1113                         ast_free(pu);
1114                         return NULL;
1115                 }
1116
1117                 /* Check if requested parking space is in use. */
1118                 AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1119                         if (cur->parkingnum == parking_space) {
1120                                 ast_log(LOG_WARNING, "PARKINGEXTEN=%d is already in use in %s\n",
1121                                         parking_space, parkinglot->name);
1122                                 AST_LIST_UNLOCK(&parkinglot->parkings);
1123                                 parkinglot_unref(parkinglot);
1124                                 ast_free(pu);
1125                                 return NULL;
1126                         }
1127                 }
1128         } else {
1129                 /* PARKINGEXTEN is empty, so find a usable extension in the lot to park the call */
1130                 int start; /* The first slot we look in the parkinglot. It can be randomized. */
1131                 int start_checked = 0; /* flag raised once the first slot is checked */
1132
1133                 /* If using randomize mode, set start to random position on parking range */
1134                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
1135                         start = ast_random() % (parkinglot->cfg.parking_stop - parkinglot->cfg.parking_start + 1);
1136                         start += parkinglot->cfg.parking_start;
1137                 } else if (parkinglot->cfg.parkfindnext
1138                         && parkinglot->cfg.parking_start <= parkinglot->next_parking_space
1139                         && parkinglot->next_parking_space <= parkinglot->cfg.parking_stop) {
1140                         /* Start looking with the next parking space in the lot. */
1141                         start = parkinglot->next_parking_space;
1142                 } else {
1143                         /* Otherwise, just set it to the start position. */
1144                         start = parkinglot->cfg.parking_start;
1145                 }
1146
1147                 /* free parking extension linear search: O(n^2) */
1148                 for (i = start; ; i++) {
1149                         /* If we are past the end, wrap around to the first parking slot*/
1150                         if (i == parkinglot->cfg.parking_stop + 1) {
1151                                 i = parkinglot->cfg.parking_start;
1152                         }
1153
1154                         if (i == start) {
1155                                 /* At this point, if start_checked, we've exhausted all the possible slots. */
1156                                 if (start_checked) {
1157                                         break;
1158                                 } else {
1159                                         start_checked = 1;
1160                                 }
1161                         }
1162
1163                         /* Search the list of parked calls already in use for i. If we find it, it's in use. */
1164                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
1165                                 if (cur->parkingnum == i) {
1166                                         break;
1167                                 }
1168                         }
1169                         if (!cur) {
1170                                 /* We found a parking space. */
1171                                 parking_space = i;
1172                                 break;
1173                         }
1174                 }
1175                 if (parking_space == -1) {
1176                         /* We did not find a parking space.  Lot is full. */
1177                         ast_log(LOG_WARNING, "No more parking spaces in %s\n", parkinglot->name);
1178                         AST_LIST_UNLOCK(&parkinglot->parkings);
1179                         parkinglot_unref(parkinglot);
1180                         ast_free(pu);
1181                         return NULL;
1182                 }
1183         }
1184
1185         /* Prepare for next parking space search. */
1186         parkinglot->next_parking_space = parking_space + 1;
1187
1188         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
1189         pu->notquiteyet = 1;
1190         pu->parkingnum = parking_space;
1191         pu->parkinglot = parkinglot;
1192         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
1193
1194         return pu;
1195 }
1196
1197 /* Park a call */
1198 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
1199 {
1200         struct parkeduser *pu = args->pu;
1201         const char *event_from;         /*!< Channel name that is parking the call. */
1202         char app_data[AST_MAX_EXTENSION + AST_MAX_CONTEXT];
1203
1204         if (pu == NULL) {
1205                 args->pu = pu = park_space_reserve(chan, peer, args);
1206                 if (pu == NULL) {
1207                         return -1;
1208                 }
1209         }
1210
1211         ast_channel_appl_set(chan, "Parked Call");
1212         ast_channel_data_set(chan, NULL);
1213
1214         pu->chan = chan;
1215
1216         /* Put the parked channel on hold if we have two different channels */
1217         if (chan != peer) {
1218                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1219                         pu->hold_method = AST_CONTROL_RINGING;
1220                         ast_indicate(chan, AST_CONTROL_RINGING);
1221                 } else {
1222                         pu->hold_method = AST_CONTROL_HOLD;
1223                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1224                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1225                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1226                 }
1227         }
1228
1229         pu->start = ast_tvnow();
1230         /* XXX This line was changed to not use get_parkingtime. This is just a placeholder message, because
1231          * likely this entire function is going away.
1232          */
1233         pu->parkingtime = args->timeout;
1234         if (args->extout)
1235                 *(args->extout) = pu->parkingnum;
1236
1237         if (peer) {
1238                 event_from = S_OR(args->orig_chan_name, ast_channel_name(peer));
1239
1240                 /*
1241                  * This is so ugly that it hurts, but implementing
1242                  * get_base_channel() on local channels could have ugly side
1243                  * effects.  We could have
1244                  * transferer<->local;1<->local;2<->parking and we need the
1245                  * callback name to be that of transferer.  Since local;1/2 have
1246                  * the same name we can be tricky and just grab the bridged
1247                  * channel from the other side of the local.
1248                  */
1249                 if (!strcasecmp(ast_channel_tech(peer)->type, "Local")) {
1250                         struct ast_channel *tmpchan, *base_peer;
1251                         char other_side[AST_CHANNEL_NAME];
1252                         char *c;
1253
1254                         ast_copy_string(other_side, event_from, sizeof(other_side));
1255                         if ((c = strrchr(other_side, ';'))) {
1256                                 *++c = '1';
1257                         }
1258                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
1259                                 ast_channel_lock(tmpchan);
1260                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
1261                                         ast_copy_string(pu->peername, ast_channel_name(base_peer), sizeof(pu->peername));
1262                                 }
1263                                 ast_channel_unlock(tmpchan);
1264                                 tmpchan = ast_channel_unref(tmpchan);
1265                         }
1266                 } else {
1267                         ast_copy_string(pu->peername, event_from, sizeof(pu->peername));
1268                 }
1269         } else {
1270                 event_from = S_OR(pbx_builtin_getvar_helper(chan, "BLINDTRANSFER"),
1271                         ast_channel_name(chan));
1272         }
1273
1274         /*
1275          * Remember what had been dialed, so that if the parking
1276          * expires, we try to come back to the same place
1277          */
1278         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
1279
1280         /*
1281          * If extension has options specified, they override all other
1282          * possibilities such as the returntoorigin flag and transferred
1283          * context.  Information on extension options is lost here, so
1284          * we set a flag
1285          */
1286         ast_copy_string(pu->context,
1287                 S_OR(args->return_con, S_OR(ast_channel_macrocontext(chan), ast_channel_context(chan))),
1288                 sizeof(pu->context));
1289         ast_copy_string(pu->exten,
1290                 S_OR(args->return_ext, S_OR(ast_channel_macroexten(chan), ast_channel_exten(chan))),
1291                 sizeof(pu->exten));
1292         pu->priority = args->return_pri ? args->return_pri :
1293                 (ast_channel_macropriority(chan) ? ast_channel_macropriority(chan) : ast_channel_priority(chan));
1294
1295         /*
1296          * If parking a channel directly, don't quite yet get parking
1297          * running on it.  All parking lot entries are put into the
1298          * parking lot with notquiteyet on.
1299          */
1300         if (peer != chan) {
1301                 pu->notquiteyet = 0;
1302         }
1303
1304         /* Wake up the (presumably select()ing) thread */
1305         pthread_kill(parking_thread, SIGURG);
1306         ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %u seconds\n",
1307                 ast_channel_name(chan), pu->parkingnum, pu->parkinglot->name,
1308                 pu->context, pu->exten, pu->priority, (pu->parkingtime / 1000));
1309
1310         /*** DOCUMENTATION
1311                 <managerEventInstance>
1312                         <synopsis>Raised when a call has been parked.</synopsis>
1313                         <syntax>
1314                                 <parameter name="Exten">
1315                                         <para>The parking lot extension.</para>
1316                                 </parameter>
1317                                 <parameter name="Parkinglot">
1318                                         <para>The name of the parking lot.</para>
1319                                 </parameter>
1320                                 <parameter name="From">
1321                                         <para>The name of the channel that parked the call.</para>
1322                                 </parameter>
1323                         </syntax>
1324                         <see-also>
1325                                 <ref type="application">Park</ref>
1326                                 <ref type="manager">Park</ref>
1327                                 <ref type="managerEvent">ParkedCallTimeOut</ref>
1328                                 <ref type="managerEvent">ParkedCallGiveUp</ref>
1329                         </see-also>
1330                 </managerEventInstance>
1331         ***/
1332         ast_manager_event(chan, EVENT_FLAG_CALL, "ParkedCall",
1333                 "Exten: %s\r\n"
1334                 "Channel: %s\r\n"
1335                 "Parkinglot: %s\r\n"
1336                 "From: %s\r\n"
1337                 "Timeout: %ld\r\n"
1338                 "CallerIDNum: %s\r\n"
1339                 "CallerIDName: %s\r\n"
1340                 "ConnectedLineNum: %s\r\n"
1341                 "ConnectedLineName: %s\r\n"
1342                 "Uniqueid: %s\r\n",
1343                 pu->parkingexten, ast_channel_name(chan), pu->parkinglot->name, event_from,
1344                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
1345                 S_COR(ast_channel_caller(chan)->id.number.valid, ast_channel_caller(chan)->id.number.str, "<unknown>"),
1346                 S_COR(ast_channel_caller(chan)->id.name.valid, ast_channel_caller(chan)->id.name.str, "<unknown>"),
1347                 S_COR(ast_channel_connected(chan)->id.number.valid, ast_channel_connected(chan)->id.number.str, "<unknown>"),
1348                 S_COR(ast_channel_connected(chan)->id.name.valid, ast_channel_connected(chan)->id.name.str, "<unknown>"),
1349                 ast_channel_uniqueid(chan)
1350                 );
1351         ast_debug(4, "peer: %s\n", peer ? ast_channel_name(peer) : "-No peer-");
1352         ast_debug(4, "args->orig_chan_name: %s\n", args->orig_chan_name ? args->orig_chan_name : "-none-");
1353         ast_debug(4, "pu->peername: %s\n", pu->peername);
1354         ast_debug(4, "AMI ParkedCall Channel: %s\n", ast_channel_name(chan));
1355         ast_debug(4, "AMI ParkedCall From: %s\n", event_from);
1356
1357         if (peer && adsipark && ast_adsi_available(peer)) {
1358                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
1359                 ast_adsi_unload_session(peer);
1360         }
1361
1362         snprintf(app_data, sizeof(app_data), "%s,%s", pu->parkingexten,
1363                 pu->parkinglot->name);
1364
1365         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
1366
1367         /* Only say number if it's a number and the channel hasn't been masqueraded away */
1368         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE)
1369                 && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(ast_channel_name(peer), args->orig_chan_name))) {
1370                 /*
1371                  * If a channel is masqueraded into peer while playing back the
1372                  * parking space number do not continue playing it back.  This
1373                  * is the case if an attended transfer occurs.
1374                  */
1375                 ast_set_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1376                 /* Tell the peer channel the number of the parking space */
1377                 ast_say_digits(peer, pu->parkingnum, "", ast_channel_language(peer));
1378                 ast_clear_flag(ast_channel_flags(peer), AST_FLAG_MASQ_NOSTREAM);
1379         }
1380         if (peer == chan) { /* pu->notquiteyet = 1 */
1381                 /* Wake up parking thread if we're really done */
1382                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
1383                         pu->hold_method = AST_CONTROL_RINGING;
1384                         ast_indicate(chan, AST_CONTROL_RINGING);
1385                 } else {
1386                         pu->hold_method = AST_CONTROL_HOLD;
1387                         ast_indicate_data(chan, AST_CONTROL_HOLD,
1388                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
1389                                 !ast_strlen_zero(pu->parkinglot->cfg.mohclass) ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0);
1390                 }
1391                 pu->notquiteyet = 0;
1392                 pthread_kill(parking_thread, SIGURG);
1393         }
1394         return 0;
1395 }
1396
1397 /*!
1398  * \brief Park call via masqueraded channel and announce parking spot on peer channel.
1399  *
1400  * \param rchan the real channel to be parked
1401  * \param peer the channel to have the parking read to.
1402  * \param args Additional parking options when parking a call.
1403  *
1404  * \retval 0 on success.
1405  * \retval -1 on failure.
1406  */
1407 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1408 {
1409         struct ast_channel *chan;
1410
1411         /* Make a new, channel that we'll use to masquerade in the real one */
1412         chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, ast_channel_accountcode(rchan), ast_channel_exten(rchan),
1413                 ast_channel_context(rchan), ast_channel_linkedid(rchan), ast_channel_amaflags(rchan), "Parked/%s", ast_channel_name(rchan));
1414         if (!chan) {
1415                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1416                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1417                         if (peer == rchan) {
1418                                 /* Only have one channel to worry about. */
1419                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1420                         } else if (peer) {
1421                                 /* Have two different channels to worry about. */
1422                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1423                         }
1424                 }
1425                 return -1;
1426         }
1427
1428         args->pu = park_space_reserve(rchan, peer, args);
1429         if (!args->pu) {
1430                 ast_hangup(chan);
1431                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1432                         if (peer == rchan) {
1433                                 /* Only have one channel to worry about. */
1434                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1435                         } else if (peer) {
1436                                 /* Have two different channels to worry about. */
1437                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1438                         }
1439                 }
1440                 return -1;
1441         }
1442
1443         /* Make formats okay */
1444         ast_format_copy(ast_channel_readformat(chan), ast_channel_readformat(rchan));
1445         ast_format_copy(ast_channel_writeformat(chan), ast_channel_writeformat(rchan));
1446
1447         if (ast_channel_masquerade(chan, rchan)) {
1448                 park_space_abort(args->pu);
1449                 args->pu = NULL;
1450                 ast_hangup(chan);
1451                 if (!ast_test_flag(args, AST_PARK_OPT_SILENCE)) {
1452                         if (peer == rchan) {
1453                                 /* Only have one channel to worry about. */
1454                                 ast_stream_and_wait(peer, "pbx-parkingfailed", "");
1455                         } else if (peer) {
1456                                 /* Have two different channels to worry about. */
1457                                 play_message_on_chan(peer, rchan, "failure message", "pbx-parkingfailed");
1458                         }
1459                 }
1460                 return -1;
1461         }
1462
1463         /* Setup the extensions and such */
1464         set_c_e_p(chan, ast_channel_context(rchan), ast_channel_exten(rchan), ast_channel_priority(rchan));
1465
1466         /* Setup the macro extension and such */
1467         ast_channel_macrocontext_set(chan, ast_channel_macrocontext(rchan));
1468         ast_channel_macroexten_set(chan, ast_channel_macroexten(rchan));
1469         ast_channel_macropriority_set(chan, ast_channel_macropriority(rchan));
1470
1471         /* Manually do the masquerade to make sure it is complete. */
1472         ast_do_masquerade(chan);
1473
1474         if (peer == rchan) {
1475                 peer = chan;
1476         }
1477
1478         /* parking space reserved, return code check unnecessary */
1479         park_call_full(chan, peer, args);
1480
1481         return 0;
1482 }
1483
1484 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)
1485 {
1486         int res;
1487         char *parse;
1488         const char *app_data;
1489         struct ast_exten *exten;
1490         struct park_app_args app_args;
1491         struct ast_park_call_args args = {
1492                 .timeout = timeout,
1493                 .extout = extout,
1494         };
1495
1496         if (parker) {
1497                 args.orig_chan_name = ast_strdupa(ast_channel_name(parker));
1498         }
1499         if (!park_exten || !park_context) {
1500                 return masq_park_call(park_me, parker, &args);
1501         }
1502
1503         /*
1504          * Determiine if the specified park extension has an exclusive
1505          * parking lot to use.
1506          */
1507         if (parker && parker != park_me) {
1508                 ast_autoservice_start(park_me);
1509         }
1510         exten = get_parking_exten(park_exten, parker, park_context);
1511         if (exten) {
1512                 app_data = ast_get_extension_app_data(exten);
1513                 if (!app_data) {
1514                         app_data = "";
1515                 }
1516                 parse = ast_strdupa(app_data);
1517                 AST_STANDARD_APP_ARGS(app_args, parse);
1518
1519                 if (!ast_strlen_zero(app_args.pl_name)) {
1520                         /* Find the specified exclusive parking lot */
1521                         args.parkinglot = find_parkinglot(app_args.pl_name);
1522                         if (!args.parkinglot && parkeddynamic) {
1523                                 args.parkinglot = create_dynamic_parkinglot(app_args.pl_name, park_me);
1524                         }
1525                 }
1526         }
1527         if (parker && parker != park_me) {
1528                 ast_autoservice_stop(park_me);
1529         }
1530
1531         res = masq_park_call(park_me, parker, &args);
1532         if (args.parkinglot) {
1533                 parkinglot_unref(args.parkinglot);
1534         }
1535         return res;
1536 }
1537
1538 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1539 {
1540         struct ast_park_call_args args = {
1541                 .timeout = timeout,
1542                 .extout = extout,
1543         };
1544
1545         if (peer) {
1546                 args.orig_chan_name = ast_strdupa(ast_channel_name(peer));
1547         }
1548         return masq_park_call(rchan, peer, &args);
1549 }
1550
1551 /*!
1552  * \internal
1553  * \brief Play file to specified channel.
1554  *
1555  * \param play_to Channel to play audiofile to.
1556  * \param other Channel to put in autoservice while playing file.
1557  * \param msg Descriptive name of message type being played.
1558  * \param audiofile Audio file to play.
1559  *
1560  * \retval 0 on success.
1561  * \retval -1 on error. (Couldn't play file, a channel hung up,...)
1562  */
1563 static int play_message_on_chan(struct ast_channel *play_to, struct ast_channel *other, const char *msg, const char *audiofile)
1564 {
1565         /* Put other channel in autoservice. */
1566         if (ast_autoservice_start(other)) {
1567                 return -1;
1568         }
1569         ast_autoservice_ignore(other, AST_FRAME_DTMF_BEGIN);
1570         ast_autoservice_ignore(other, AST_FRAME_DTMF_END);
1571         if (ast_stream_and_wait(play_to, audiofile, "")) {
1572                 ast_log(LOG_WARNING, "Failed to play %s '%s'!\n", msg, audiofile);
1573                 ast_autoservice_stop(other);
1574                 return -1;
1575         }
1576         if (ast_autoservice_stop(other)) {
1577                 return -1;
1578         }
1579         return 0;
1580 }
1581
1582 /*!
1583  * \internal
1584  * \brief Get the extension for a given builtin feature
1585  *
1586  * \pre expects features_lock to be readlocked
1587  *
1588  * \retval 0 success
1589  * \retval non-zero failiure
1590  */
1591 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name,
1592                 char *buf, size_t len)
1593 {
1594         SCOPED_CHANNELLOCK(lock, chan);
1595
1596         return ast_get_builtin_feature(chan, feature_name, buf, len);
1597 }
1598
1599 static void set_config_flags(struct ast_channel *chan, struct ast_bridge_config *config)
1600 {
1601 /* BUGBUG there is code that checks AST_BRIDGE_IGNORE_SIGS but no code to set it. */
1602 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_0 but no code to set it. */
1603 /* BUGBUG there is code that checks AST_BRIDGE_REC_CHANNEL_1 but no code to set it. */
1604         ast_clear_flag(config, AST_FLAGS_ALL);
1605
1606         if (ast_test_flag(&config->features_caller, AST_FEATURE_DTMF_MASK)) {
1607                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
1608         }
1609         if (ast_test_flag(&config->features_callee, AST_FEATURE_DTMF_MASK)) {
1610                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
1611         }
1612
1613         if (!(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
1614                 RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
1615
1616                 ast_channel_lock(chan);
1617                 applicationmap = ast_get_chan_applicationmap(chan);
1618                 ast_channel_unlock(chan);
1619
1620                 if (!applicationmap) {
1621                         return;
1622                 }
1623
1624                 /* If an applicationmap exists for this channel at all, then the channel needs the DTMF flag set */
1625                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
1626         }
1627 }
1628
1629 void ast_channel_log(char *title, struct ast_channel *chan);
1630
1631 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
1632 {
1633         ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long) chan);
1634         ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
1635                 ast_channel_name(chan), ast_channel_appl(chan), ast_channel_data(chan),
1636                 ast_channel_context(chan), ast_channel_exten(chan), ast_channel_priority(chan));
1637         ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
1638                 ast_channel_accountcode(chan), ast_channel_dialcontext(chan), ast_channel_amaflags(chan),
1639                 ast_channel_macrocontext(chan), ast_channel_macroexten(chan), ast_channel_macropriority(chan));
1640         ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; uniqueID: %s; linkedID:%s\n",
1641                 ast_channel_masq(chan), ast_channel_masqr(chan),
1642                 ast_channel_uniqueid(chan), ast_channel_linkedid(chan));
1643         if (ast_channel_masqr(chan)) {
1644                 ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
1645                         ast_channel_name(ast_channel_masqr(chan)), ast_channel_cdr(ast_channel_masqr(chan)));
1646         }
1647
1648         ast_log(LOG_NOTICE, "===== done ====\n");
1649 }
1650
1651 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
1652 {
1653         const char *feature;
1654
1655         if (ast_strlen_zero(features)) {
1656                 return;
1657         }
1658
1659         for (feature = features; *feature; feature++) {
1660                 struct ast_flags *party;
1661
1662                 if (isupper(*feature)) {
1663                         party = &config->features_caller;
1664                 } else {
1665                         party = &config->features_callee;
1666                 }
1667
1668                 switch (tolower(*feature)) {
1669                 case 't' :
1670                         ast_set_flag(party, AST_FEATURE_REDIRECT);
1671                         break;
1672                 case 'k' :
1673                         ast_set_flag(party, AST_FEATURE_PARKCALL);
1674                         break;
1675                 case 'h' :
1676                         ast_set_flag(party, AST_FEATURE_DISCONNECT);
1677                         break;
1678                 case 'w' :
1679                         ast_set_flag(party, AST_FEATURE_AUTOMON);
1680                         break;
1681                 case 'x' :
1682                         ast_set_flag(party, AST_FEATURE_AUTOMIXMON);
1683                         break;
1684                 default :
1685                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
1686                         break;
1687                 }
1688         }
1689 }
1690
1691 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
1692 {
1693         if (add_features_datastore(caller, &config->features_caller, &config->features_callee)) {
1694                 /*
1695                  * If we don't return here, then when we do a builtin_atxfer we
1696                  * will copy the disconnect flags over from the atxfer to the
1697                  * callee (Party C).
1698                  */
1699                 return;
1700         }
1701
1702         add_features_datastore(callee, &config->features_callee, &config->features_caller);
1703 }
1704
1705 static void clear_dialed_interfaces(struct ast_channel *chan)
1706 {
1707         struct ast_datastore *di_datastore;
1708
1709         ast_channel_lock(chan);
1710         if ((di_datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL))) {
1711                 if (option_debug) {
1712                         ast_log(LOG_DEBUG, "Removing dialed interfaces datastore on %s since we're bridging\n", ast_channel_name(chan));
1713                 }
1714                 if (!ast_channel_datastore_remove(chan, di_datastore)) {
1715                         ast_datastore_free(di_datastore);
1716                 }
1717         }
1718         ast_channel_unlock(chan);
1719 }
1720
1721 /*!
1722  * \internal
1723  * \brief Helper to add a builtin DTMF feature hook to the features struct.
1724  * \since 12.0.0
1725  *
1726  * \param features Bridge features to setup.
1727  * \param chan Get features from this channel.
1728  * \param flags Feature flags on the channel.
1729  * \param feature_flag Feature flag to test.
1730  * \param feature_name features.conf name of feature.
1731  * \param feature_bridge Bridge feature enum to get hook callback.
1732  *
1733  * \retval 0 on success.
1734  * \retval -1 on error.
1735  */
1736 static int builtin_features_helper(struct ast_bridge_features *features, struct ast_channel *chan,
1737         struct ast_flags *flags, unsigned int feature_flag, const char *feature_name, enum ast_bridge_builtin_feature feature_bridge)
1738 {
1739         char dtmf[AST_FEATURE_MAX_LEN];
1740         int res;
1741
1742         res = 0;
1743         if (ast_test_flag(flags, feature_flag)
1744                 && !builtin_feature_get_exten(chan, feature_name, dtmf, sizeof(dtmf))
1745                 && !ast_strlen_zero(dtmf)) {
1746                 res = ast_bridge_features_enable(features, feature_bridge, dtmf, NULL, NULL,
1747                         AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
1748                 if (res) {
1749                         ast_log(LOG_ERROR, "Channel %s: Requested DTMF feature %s not available.\n",
1750                                 ast_channel_name(chan), feature_name);
1751                 }
1752         }
1753
1754         return res;
1755 }
1756
1757 /*!
1758  * \internal
1759  * \brief Setup bridge builtin features.
1760  * \since 12.0.0
1761  *
1762  * \param features Bridge features to setup.
1763  * \param chan Get features from this channel.
1764  *
1765  * \retval 0 on success.
1766  * \retval -1 on error.
1767  */
1768 static int setup_bridge_features_builtin(struct ast_bridge_features *features, struct ast_channel *chan)
1769 {
1770         struct ast_flags *flags;
1771         int res;
1772
1773         ast_channel_lock(chan);
1774         flags = ast_bridge_features_ds_get(chan);
1775         ast_channel_unlock(chan);
1776         if (!flags) {
1777                 return 0;
1778         }
1779
1780         res = 0;
1781         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "blindxfer", AST_BRIDGE_BUILTIN_BLINDTRANSFER);
1782         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "atxfer", AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER);
1783         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_DISCONNECT, "disconnect", AST_BRIDGE_BUILTIN_HANGUP);
1784         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_PARKCALL, "parkcall", AST_BRIDGE_BUILTIN_PARKCALL);
1785         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMON, "automon", AST_BRIDGE_BUILTIN_AUTOMON);
1786         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMIXMON, "automixmon", AST_BRIDGE_BUILTIN_AUTOMIXMON);
1787
1788         return res ? -1 : 0;
1789 }
1790
1791 struct dynamic_dtmf_hook_run {
1792         /*! Offset into app_name[] where the channel name that activated the hook starts. */
1793         int activated_offset;
1794         /*! Offset into app_name[] where the dynamic feature name starts. */
1795         int feature_offset;
1796         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1797         int moh_offset;
1798         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1799         int app_args_offset;
1800         /*! Application name to run. */
1801         char app_name[0];
1802 };
1803
1804 static void dynamic_dtmf_hook_callback(struct ast_bridge_channel *bridge_channel,
1805         const void *payload, size_t payload_size)
1806 {
1807         struct ast_channel *chan = bridge_channel->chan;
1808         const struct dynamic_dtmf_hook_run *run_data = payload;
1809
1810         pbx_builtin_setvar_helper(chan, "DYNAMIC_FEATURENAME",
1811                 &run_data->app_name[run_data->feature_offset]);
1812         pbx_builtin_setvar_helper(chan, "DYNAMIC_WHO_ACTIVATED",
1813                 &run_data->app_name[run_data->activated_offset]);
1814
1815         ast_bridge_channel_run_app(bridge_channel, run_data->app_name,
1816                 run_data->app_args_offset ? &run_data->app_name[run_data->app_args_offset] : NULL,
1817                 run_data->moh_offset ? &run_data->app_name[run_data->moh_offset] : NULL);
1818 }
1819
1820 static int dynamic_dtmf_hook_run_callback(struct ast_bridge_channel *bridge_channel,
1821         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
1822 {
1823         callback(bridge_channel, payload, payload_size);
1824         return 0;
1825 }
1826
1827 struct dynamic_dtmf_hook_data {
1828         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
1829         unsigned int flags;
1830         /*! Offset into app_name[] where the dynamic feature name starts. */
1831         int feature_offset;
1832         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
1833         int moh_offset;
1834         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
1835         int app_args_offset;
1836         /*! Application name to run. */
1837         char app_name[0];
1838 };
1839
1840 /*!
1841  * \internal
1842  * \brief Activated dynamic DTMF feature hook.
1843  * \since 12.0.0
1844  *
1845  * \param bridge The bridge that the channel is part of
1846  * \param bridge_channel Channel executing the feature
1847  * \param hook_pvt Private data passed in when the hook was created
1848  *
1849  * \retval 0 Keep the callback hook.
1850  * \retval -1 Remove the callback hook.
1851  */
1852 static int dynamic_dtmf_hook_trip(struct ast_bridge *bridge, struct ast_bridge_channel *bridge_channel, void *hook_pvt)
1853 {
1854         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
1855         int (*run_it)(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size);
1856         struct dynamic_dtmf_hook_run *run_data;
1857         const char *activated_name;
1858         size_t len_name;
1859         size_t len_args;
1860         size_t len_moh;
1861         size_t len_feature;
1862         size_t len_activated;
1863         size_t len_data;
1864
1865         /* Determine lengths of things. */
1866         len_name = strlen(pvt->app_name) + 1;
1867         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
1868         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
1869         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
1870         ast_channel_lock(bridge_channel->chan);
1871         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
1872         ast_channel_unlock(bridge_channel->chan);
1873         len_activated = strlen(activated_name) + 1;
1874         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
1875
1876         /* Fill in dynamic feature run hook data. */
1877         run_data = ast_alloca(len_data);
1878         run_data->app_args_offset = len_args ? len_name : 0;
1879         run_data->moh_offset = len_moh ? len_name + len_args : 0;
1880         run_data->feature_offset = len_name + len_args + len_moh;
1881         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
1882         strcpy(run_data->app_name, pvt->app_name);/* Safe */
1883         if (len_args) {
1884                 strcpy(&run_data->app_name[run_data->app_args_offset],
1885                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
1886         }
1887         if (len_moh) {
1888                 strcpy(&run_data->app_name[run_data->moh_offset],
1889                         &pvt->app_name[pvt->moh_offset]);/* Safe */
1890         }
1891         strcpy(&run_data->app_name[run_data->feature_offset],
1892                 &pvt->app_name[pvt->feature_offset]);/* Safe */
1893         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
1894
1895         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
1896                 run_it = ast_bridge_channel_write_callback;
1897         } else {
1898                 run_it = dynamic_dtmf_hook_run_callback;
1899         }
1900         run_it(bridge_channel, dynamic_dtmf_hook_callback, run_data, len_data);
1901         return 0;
1902 }
1903
1904 /*!
1905  * \internal
1906  * \brief Add a dynamic DTMF feature hook to the bridge features.
1907  * \since 12.0.0
1908  *
1909  * \param features Bridge features to setup.
1910  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
1911  * \param dtmf DTMF trigger sequence.
1912  * \param feature_name Name of the dynamic feature.
1913  * \param app_name Dialplan application name to run.
1914  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
1915  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
1916  *
1917  * \retval 0 on success.
1918  * \retval -1 on error.
1919  */
1920 static int dynamic_dtmf_hook_add(struct ast_bridge_features *features, unsigned int flags, const char *dtmf, const char *feature_name, const char *app_name, const char *app_args, const char *moh_class)
1921 {
1922         struct dynamic_dtmf_hook_data *hook_data;
1923         size_t len_name = strlen(app_name) + 1;
1924         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
1925         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
1926         size_t len_feature = strlen(feature_name) + 1;
1927         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
1928         int res;
1929
1930         /* Fill in application run hook data. */
1931         hook_data = ast_malloc(len_data);
1932         if (!hook_data) {
1933                 return -1;
1934         }
1935         hook_data->flags = flags;
1936         hook_data->app_args_offset = len_args ? len_name : 0;
1937         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
1938         hook_data->feature_offset = len_name + len_args + len_moh;
1939         strcpy(hook_data->app_name, app_name);/* Safe */
1940         if (len_args) {
1941                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
1942         }
1943         if (len_moh) {
1944                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
1945         }
1946         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
1947
1948         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
1949                 ast_free_ptr, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
1950         if (res) {
1951                 ast_free(hook_data);
1952         }
1953         return res;
1954 }
1955
1956 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
1957 {
1958         struct ast_applicationmap_item *item = obj;
1959         struct ast_bridge_features *features = arg;
1960         int *res = data;
1961
1962         *res |= dynamic_dtmf_hook_add(features,
1963                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
1964                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
1965
1966         return 0;
1967 }
1968
1969 /*!
1970  * \internal
1971  * \brief Setup bridge dynamic features.
1972  * \since 12.0.0
1973  *
1974  * \param features Bridge features to setup.
1975  * \param chan Get features from this channel.
1976  *
1977  * \retval 0 on success.
1978  * \retval -1 on error.
1979  */
1980 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
1981 {
1982         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
1983         int res = 0;
1984
1985         ast_channel_lock(chan);
1986         applicationmap = ast_get_chan_applicationmap(chan);
1987         ast_channel_unlock(chan);
1988         if (!applicationmap) {
1989                 return 0;
1990         }
1991
1992         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
1993
1994         return res;
1995 }
1996
1997 /* BUGBUG this really should be made a private function of bridging_basic.c after struct ast_call_feature is made an ao2 object. */
1998 int ast_bridge_channel_setup_features(struct ast_bridge_channel *bridge_channel)
1999 {
2000         int res = 0;
2001
2002         /* Always pass through any DTMF digits. */
2003         bridge_channel->features->dtmf_passthrough = 1;
2004
2005         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
2006         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
2007
2008         return res;
2009 }
2010
2011 static void bridge_config_set_limits_warning_values(struct ast_bridge_config *config, struct ast_bridge_features_limits *limits)
2012 {
2013         if (config->end_sound) {
2014                 ast_string_field_set(limits, duration_sound, config->end_sound);
2015         }
2016
2017         if (config->warning_sound) {
2018                 ast_string_field_set(limits, warning_sound, config->warning_sound);
2019         }
2020
2021         if (config->start_sound) {
2022                 ast_string_field_set(limits, connect_sound, config->start_sound);
2023         }
2024
2025         limits->frequency = config->warning_freq;
2026         limits->warning = config->play_warning;
2027 }
2028
2029 /*!
2030  * \internal brief Setup limit hook structures on calls that need limits
2031  *
2032  * \param config ast_bridge_config which provides the limit data
2033  * \param caller_limits pointer to an ast_bridge_features_limits struct which will store the caller side limits
2034  * \param callee_limits pointer to an ast_bridge_features_limits struct which will store the callee side limits
2035  */
2036 static void bridge_config_set_limits(struct ast_bridge_config *config, struct ast_bridge_features_limits *caller_limits, struct ast_bridge_features_limits *callee_limits)
2037 {
2038         if (ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING)) {
2039                 bridge_config_set_limits_warning_values(config, caller_limits);
2040         }
2041
2042         if (ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING)) {
2043                 bridge_config_set_limits_warning_values(config, callee_limits);
2044         }
2045
2046         caller_limits->duration = config->timelimit;
2047         callee_limits->duration = config->timelimit;
2048 }
2049
2050 /*!
2051  * \internal
2052  * \brief Check if Monitor needs to be started on a channel.
2053  * \since 12.0.0
2054  *
2055  * \param chan The bridge considers this channel the caller.
2056  * \param peer The bridge considers this channel the callee.
2057  *
2058  * \return Nothing
2059  */
2060 static void bridge_check_monitor(struct ast_channel *chan, struct ast_channel *peer)
2061 {
2062         const char *value;
2063         const char *monitor_args = NULL;
2064         struct ast_channel *monitor_chan = NULL;
2065
2066         ast_channel_lock(chan);
2067         value = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR");
2068         if (!ast_strlen_zero(value)) {
2069                 monitor_args = ast_strdupa(value);
2070                 monitor_chan = chan;
2071         }
2072         ast_channel_unlock(chan);
2073         if (!monitor_chan) {
2074                 ast_channel_lock(peer);
2075                 value = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR");
2076                 if (!ast_strlen_zero(value)) {
2077                         monitor_args = ast_strdupa(value);
2078                         monitor_chan = peer;
2079                 }
2080                 ast_channel_unlock(peer);
2081         }
2082         if (monitor_chan) {
2083                 struct ast_app *monitor_app;
2084
2085                 monitor_app = pbx_findapp("Monitor");
2086                 if (monitor_app) {
2087                         pbx_exec(monitor_chan, monitor_app, monitor_args);
2088                 }
2089         }
2090 }
2091
2092 /*!
2093  * \internal
2094  * \brief Send the peer channel on its way on bridge start failure.
2095  * \since 12.0.0
2096  *
2097  * \param chan Chan to put into autoservice.
2098  * \param peer Chan to send to after bridge goto or run hangup handlers and hangup.
2099  *
2100  * \return Nothing
2101  */
2102 static void bridge_failed_peer_goto(struct ast_channel *chan, struct ast_channel *peer)
2103 {
2104         if (ast_bridge_setup_after_goto(peer)
2105                 || ast_pbx_start(peer)) {
2106                 ast_autoservice_chan_hangup_peer(chan, peer);
2107         }
2108 }
2109
2110 static int pre_bridge_setup(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config,
2111                 struct ast_bridge_features *chan_features, struct ast_bridge_features *peer_features)
2112 {
2113         int res;
2114
2115         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
2116         add_features_datastores(chan, peer, config);
2117
2118         /*
2119          * This is an interesting case.  One example is if a ringing
2120          * channel gets redirected to an extension that picks up a
2121          * parked call.  This will make sure that the call taken out of
2122          * parking gets told that the channel it just got bridged to is
2123          * still ringing.
2124          */
2125         if (ast_channel_state(chan) == AST_STATE_RINGING
2126                 && ast_channel_visible_indication(peer) != AST_CONTROL_RINGING) {
2127                 ast_indicate(peer, AST_CONTROL_RINGING);
2128         }
2129
2130         bridge_check_monitor(chan, peer);
2131
2132         set_config_flags(chan, config);
2133
2134         /* Answer if need be */
2135         if (ast_channel_state(chan) != AST_STATE_UP) {
2136                 if (ast_raw_answer(chan)) {
2137                         return -1;
2138                 }
2139         }
2140
2141 #ifdef FOR_DEBUG
2142         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
2143         ast_channel_log("Pre-bridge CHAN Channel info", chan);
2144         ast_channel_log("Pre-bridge PEER Channel info", peer);
2145 #endif
2146
2147         /*
2148          * If we are bridging a call, stop worrying about forwarding
2149          * loops.  We presume that if a call is being bridged, that the
2150          * humans in charge know what they're doing.  If they don't,
2151          * well, what can we do about that?
2152          */
2153         clear_dialed_interfaces(chan);
2154         clear_dialed_interfaces(peer);
2155
2156         res = 0;
2157         ast_channel_lock(chan);
2158         res |= ast_bridge_features_ds_set(chan, &config->features_caller);
2159         ast_channel_unlock(chan);
2160         ast_channel_lock(peer);
2161         res |= ast_bridge_features_ds_set(peer, &config->features_callee);
2162         ast_channel_unlock(peer);
2163
2164         if (res) {
2165                 return -1;
2166         }
2167
2168         if (config->timelimit) {
2169                 struct ast_bridge_features_limits call_duration_limits_chan;
2170                 struct ast_bridge_features_limits call_duration_limits_peer;
2171                 int abandon_call = 0; /* TRUE if set limits fails so we can abandon the call. */
2172
2173                 if (ast_bridge_features_limits_construct(&call_duration_limits_chan)) {
2174                         ast_log(LOG_ERROR, "Could not construct caller duration limits. Bridge canceled.\n");
2175
2176                         return -1;
2177                 }
2178
2179                 if (ast_bridge_features_limits_construct(&call_duration_limits_peer)) {
2180                         ast_log(LOG_ERROR, "Could not construct callee duration limits. Bridge canceled.\n");
2181                         ast_bridge_features_limits_destroy(&call_duration_limits_chan);
2182
2183                         return -1;
2184                 }
2185
2186                 bridge_config_set_limits(config, &call_duration_limits_chan, &call_duration_limits_peer);
2187
2188                 if (ast_bridge_features_set_limits(chan_features, &call_duration_limits_chan, 0)) {
2189                         abandon_call = 1;
2190                 }
2191                 if (ast_bridge_features_set_limits(peer_features, &call_duration_limits_peer, 0)) {
2192                         abandon_call = 1;
2193                 }
2194
2195                 /* At this point we are done with the limits structs since they have been copied to the individual feature sets. */
2196                 ast_bridge_features_limits_destroy(&call_duration_limits_chan);
2197                 ast_bridge_features_limits_destroy(&call_duration_limits_peer);
2198
2199                 if (abandon_call) {
2200                         ast_log(LOG_ERROR, "Could not set duration limits on one or more sides of the call. Bridge canceled.\n");
2201                         return -1;
2202                 }
2203         }
2204
2205         return 0;
2206 }
2207
2208 /*!
2209  * \brief bridge the call and set CDR
2210  *
2211  * \param chan The bridge considers this channel the caller.
2212  * \param peer The bridge considers this channel the callee.
2213  * \param config Configuration for this bridge.
2214  *
2215  * Set start time, check for two channels,check if monitor on
2216  * check for feature activation, create new CDR
2217  * \retval res on success.
2218  * \retval -1 on failure to bridge.
2219  */
2220 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2221 {
2222         int res;
2223         struct ast_bridge *bridge;
2224         struct ast_bridge_features chan_features;
2225         struct ast_bridge_features *peer_features;
2226
2227         /* Setup features. */
2228         res = ast_bridge_features_init(&chan_features);
2229         peer_features = ast_bridge_features_new();
2230         if (res || !peer_features) {
2231                 ast_bridge_features_destroy(peer_features);
2232                 ast_bridge_features_cleanup(&chan_features);
2233                 bridge_failed_peer_goto(chan, peer);
2234                 return -1;
2235         }
2236
2237         if (pre_bridge_setup(chan, peer, config, &chan_features, peer_features)) {
2238                 ast_bridge_features_destroy(peer_features);
2239                 ast_bridge_features_cleanup(&chan_features);
2240                 bridge_failed_peer_goto(chan, peer);
2241                 return -1;
2242         }
2243
2244         /* Create bridge */
2245         bridge = ast_bridge_basic_new();
2246         if (!bridge) {
2247                 ast_bridge_features_destroy(peer_features);
2248                 ast_bridge_features_cleanup(&chan_features);
2249                 bridge_failed_peer_goto(chan, peer);
2250                 return -1;
2251         }
2252
2253         /* Put peer into the bridge */
2254         if (ast_bridge_impart(bridge, peer, NULL, peer_features, 1)) {
2255                 ast_bridge_destroy(bridge);
2256                 ast_bridge_features_cleanup(&chan_features);
2257                 bridge_failed_peer_goto(chan, peer);
2258                 return -1;
2259         }
2260
2261         /* Join bridge */
2262         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL, 1);
2263
2264         /*
2265          * If the bridge was broken for a hangup that isn't real, then
2266          * don't run the h extension, because the channel isn't really
2267          * hung up.  This should really only happen with
2268          * AST_SOFTHANGUP_ASYNCGOTO.
2269          */
2270         res = -1;
2271         ast_channel_lock(chan);
2272         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
2273                 res = 0;
2274         }
2275         ast_channel_unlock(chan);
2276
2277         ast_bridge_features_cleanup(&chan_features);
2278
2279 /* BUGBUG this is used by Dial and FollowMe for CDR information.  By Queue for Queue stats like CDRs. */
2280         if (res && config->end_bridge_callback) {
2281                 config->end_bridge_callback(config->end_bridge_callback_data);
2282         }
2283
2284         return res;
2285 }
2286
2287 /*! \brief Output parking event to manager */
2288 static void post_manager_event(const char *s, struct parkeduser *pu)
2289 {
2290         manager_event(EVENT_FLAG_CALL, s,
2291                 "Exten: %s\r\n"
2292                 "Channel: %s\r\n"
2293                 "Parkinglot: %s\r\n"
2294                 "CallerIDNum: %s\r\n"
2295                 "CallerIDName: %s\r\n"
2296                 "ConnectedLineNum: %s\r\n"
2297                 "ConnectedLineName: %s\r\n"
2298                 "UniqueID: %s\r\n",
2299                 pu->parkingexten,
2300                 ast_channel_name(pu->chan),
2301                 pu->parkinglot->name,
2302                 S_COR(ast_channel_caller(pu->chan)->id.number.valid, ast_channel_caller(pu->chan)->id.number.str, "<unknown>"),
2303                 S_COR(ast_channel_caller(pu->chan)->id.name.valid, ast_channel_caller(pu->chan)->id.name.str, "<unknown>"),
2304                 S_COR(ast_channel_connected(pu->chan)->id.number.valid, ast_channel_connected(pu->chan)->id.number.str, "<unknown>"),
2305                 S_COR(ast_channel_connected(pu->chan)->id.name.valid, ast_channel_connected(pu->chan)->id.name.str, "<unknown>"),
2306                 ast_channel_uniqueid(pu->chan)
2307                 );
2308 }
2309
2310 static char *callback_dialoptions(struct ast_flags *features_callee, struct ast_flags *features_caller, char *options, size_t len)
2311 {
2312         int i = 0;
2313         enum {
2314                 OPT_CALLEE_REDIRECT   = 't',
2315                 OPT_CALLER_REDIRECT   = 'T',
2316                 OPT_CALLEE_AUTOMON    = 'w',
2317                 OPT_CALLER_AUTOMON    = 'W',
2318                 OPT_CALLEE_DISCONNECT = 'h',
2319                 OPT_CALLER_DISCONNECT = 'H',
2320                 OPT_CALLEE_PARKCALL   = 'k',
2321                 OPT_CALLER_PARKCALL   = 'K',
2322         };
2323
2324         memset(options, 0, len);
2325         if (ast_test_flag(features_caller, AST_FEATURE_REDIRECT) && i < len) {
2326                 options[i++] = OPT_CALLER_REDIRECT;
2327         }
2328         if (ast_test_flag(features_caller, AST_FEATURE_AUTOMON) && i < len) {
2329                 options[i++] = OPT_CALLER_AUTOMON;
2330         }
2331         if (ast_test_flag(features_caller, AST_FEATURE_DISCONNECT) && i < len) {
2332                 options[i++] = OPT_CALLER_DISCONNECT;
2333         }
2334         if (ast_test_flag(features_caller, AST_FEATURE_PARKCALL) && i < len) {
2335                 options[i++] = OPT_CALLER_PARKCALL;
2336         }
2337
2338         if (ast_test_flag(features_callee, AST_FEATURE_REDIRECT) && i < len) {
2339                 options[i++] = OPT_CALLEE_REDIRECT;
2340         }
2341         if (ast_test_flag(features_callee, AST_FEATURE_AUTOMON) && i < len) {
2342                 options[i++] = OPT_CALLEE_AUTOMON;
2343         }
2344         if (ast_test_flag(features_callee, AST_FEATURE_DISCONNECT) && i < len) {
2345                 options[i++] = OPT_CALLEE_DISCONNECT;
2346         }
2347         if (ast_test_flag(features_callee, AST_FEATURE_PARKCALL) && i < len) {
2348                 options[i++] = OPT_CALLEE_PARKCALL;
2349         }
2350
2351         return options;
2352 }
2353
2354 /*!
2355  * \internal
2356  * \brief Run management on a parked call.
2357  *
2358  * \note The parkinglot parkings list is locked on entry.
2359  *
2360  * \retval TRUE if the parking completed.
2361  */
2362 static int manage_parked_call(struct parkeduser *pu, const struct pollfd *pfds, int nfds, struct pollfd **new_pfds, int *new_nfds, int *ms)
2363 {
2364         struct ast_channel *chan = pu->chan;    /* shorthand */
2365         int tms;        /* timeout for this item */
2366         int x;          /* fd index in channel */
2367
2368         tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
2369         if (tms > pu->parkingtime) {
2370                 /*
2371                  * Call has been parked too long.
2372                  * Stop entertaining the caller.
2373                  */
2374                 switch (pu->hold_method) {
2375                 case AST_CONTROL_HOLD:
2376                         ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
2377                         break;
2378                 case AST_CONTROL_RINGING:
2379                         ast_indicate(pu->chan, -1);
2380                         break;
2381                 default:
2382                         break;
2383                 }
2384                 pu->hold_method = 0;
2385
2386                 /* Get chan, exten from derived kludge */
2387                 if (pu->peername[0]) {
2388                         char *peername;
2389                         char *dash;
2390                         char *peername_flat; /* using something like DAHDI/52 for an extension name is NOT a good idea */
2391                         char parkingslot[AST_MAX_EXTENSION]; /* buffer for parkinglot slot number */
2392                         int i;
2393
2394                         peername = ast_strdupa(pu->peername);
2395                         dash = strrchr(peername, '-');
2396                         if (dash) {
2397                                 *dash = '\0';
2398                         }
2399
2400                         peername_flat = ast_strdupa(peername);
2401                         for (i = 0; peername_flat[i]; i++) {
2402                                 if (peername_flat[i] == '/') {
2403                                         peername_flat[i] = '_';
2404                                 }
2405                         }
2406
2407                         if (!ast_context_find_or_create(NULL, NULL, parking_con_dial, registrar)) {
2408                                 ast_log(LOG_ERROR,
2409                                         "Parking dial context '%s' does not exist and unable to create\n",
2410                                         parking_con_dial);
2411                         } else {
2412                                 char returnexten[AST_MAX_EXTENSION];
2413                                 char comebackdialtime[AST_MAX_EXTENSION];
2414                                 struct ast_datastore *features_datastore;
2415                                 struct ast_dial_features *dialfeatures;
2416
2417                                 if (!strncmp(peername, "Parked/", 7)) {
2418                                         peername += 7;
2419                                 }
2420
2421                                 ast_channel_lock(chan);
2422                                 features_datastore = ast_channel_datastore_find(chan, &dial_features_info,
2423                                         NULL);
2424                                 if (features_datastore && (dialfeatures = features_datastore->data)) {
2425                                         char buf[MAX_DIAL_FEATURE_OPTIONS] = {0,};
2426
2427                                         snprintf(returnexten, sizeof(returnexten), "%s,%u,%s", peername,
2428                                                 pu->parkinglot->cfg.comebackdialtime,
2429                                                 callback_dialoptions(&dialfeatures->peer_features,
2430                                                         &dialfeatures->my_features, buf, sizeof(buf)));
2431                                 } else { /* Existing default */
2432                                         ast_log(LOG_NOTICE, "Dial features not found on %s, using default!\n",
2433                                                 ast_channel_name(chan));
2434                                         snprintf(returnexten, sizeof(returnexten), "%s,%u,t", peername,
2435                                                 pu->parkinglot->cfg.comebackdialtime);
2436                                 }
2437                                 ast_channel_unlock(chan);
2438
2439                                 snprintf(comebackdialtime, sizeof(comebackdialtime), "%u",
2440                                                 pu->parkinglot->cfg.comebackdialtime);
2441                                 pbx_builtin_setvar_helper(chan, "COMEBACKDIALTIME", comebackdialtime);
2442
2443                                 pbx_builtin_setvar_helper(chan, "PARKER", peername);
2444
2445                         }
2446
2447                         snprintf(parkingslot, sizeof(parkingslot), "%d", pu->parkingnum);
2448                         pbx_builtin_setvar_helper(chan, "PARKINGSLOT", parkingslot);
2449                         pbx_builtin_setvar_helper(chan, "PARKEDLOT", pu->parkinglot->name);
2450
2451                         if (pu->options_specified) {
2452                                 /*
2453                                  * Park() was called with overriding return arguments, respect
2454                                  * those arguments.
2455                                  */
2456                                 set_c_e_p(chan, pu->context, pu->exten, pu->priority);
2457                         } else if (pu->parkinglot->cfg.comebacktoorigin) {
2458                                 set_c_e_p(chan, parking_con_dial, peername_flat, 1);
2459                         } else {
2460                                 /* Handle fallback when extensions don't exist here since that logic was removed from pbx */
2461                                 if (ast_exists_extension(chan, pu->parkinglot->cfg.comebackcontext, peername_flat, 1, NULL)) {
2462                                         set_c_e_p(chan, pu->parkinglot->cfg.comebackcontext, peername_flat, 1);
2463                                 } else if (ast_exists_extension(chan, pu->parkinglot->cfg.comebackcontext, "s", 1, NULL)) {
2464                                         ast_verb(2, "Can not start %s at %s,%s,1. Using 's@%s' instead.\n", ast_channel_name(chan),
2465                                                 pu->parkinglot->cfg.comebackcontext, peername_flat, pu->parkinglot->cfg.comebackcontext);
2466                                         set_c_e_p(chan, pu->parkinglot->cfg.comebackcontext, "s", 1);
2467                                 } else {
2468                                         ast_verb(2, "Can not start %s at %s,%s,1 and exten 's@%s' does not exist. Using 's@default'\n",
2469                                                 ast_channel_name(chan),
2470                                                 pu->parkinglot->cfg.comebackcontext, peername_flat,
2471                                                 pu->parkinglot->cfg.comebackcontext);
2472                                         set_c_e_p(chan, "default", "s", 1);
2473                                 }
2474                         }
2475                 } else {
2476                         /*
2477                          * They've been waiting too long, send them back to where they
2478                          * came.  Theoretically they should have their original
2479                          * extensions and such, but we copy to be on the safe side.
2480                          */
2481                         set_c_e_p(chan, pu->context, pu->exten, pu->priority);
2482                 }
2483                 post_manager_event("ParkedCallTimeOut", pu);
2484
2485                 ast_verb(2, "Timeout for %s parked on %d (%s). Returning to %s,%s,%d\n",
2486                         ast_channel_name(pu->chan), pu->parkingnum, pu->parkinglot->name, ast_channel_context(pu->chan),
2487                         ast_channel_exten(pu->chan), ast_channel_priority(pu->chan));
2488
2489                 /* Start up the PBX, or hang them up */
2490                 if (ast_pbx_start(chan))  {
2491                         ast_log(LOG_WARNING,
2492                                 "Unable to restart the PBX for user on '%s', hanging them up...\n",
2493                                 ast_channel_name(pu->chan));
2494                         ast_hangup(chan);
2495                 }
2496
2497                 /* And take them out of the parking lot */
2498                 return 1;
2499         }
2500
2501         /* still within parking time, process descriptors */
2502         if (pfds) {
2503                 for (x = 0; x < AST_MAX_FDS; x++) {
2504                         struct ast_frame *f;
2505                         int y;
2506
2507                         if (!ast_channel_fd_isset(chan, x)) {
2508                                 continue;       /* nothing on this descriptor */
2509                         }
2510
2511                         for (y = 0; y < nfds; y++) {
2512                                 if (pfds[y].fd == ast_channel_fd(chan, x)) {
2513                                         /* Found poll record! */
2514                                         break;
2515                                 }
2516                         }
2517                         if (y == nfds) {
2518                                 /* Not found */
2519                                 continue;
2520                         }
2521
2522                         if (!(pfds[y].revents & (POLLIN | POLLERR | POLLPRI))) {
2523                                 /* Next x */
2524                                 continue;
2525                         }
2526
2527                         if (pfds[y].revents & POLLPRI) {
2528                                 ast_set_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
2529                         } else {
2530                                 ast_clear_flag(ast_channel_flags(chan), AST_FLAG_EXCEPTION);
2531                         }
2532                         ast_channel_fdno_set(chan, x);
2533
2534                         /* See if they need servicing */
2535                         f = ast_read(pu->chan);
2536                         /* Hangup? */
2537                         if (!f || (f->frametype == AST_FRAME_CONTROL
2538                                 && f->subclass.integer == AST_CONTROL_HANGUP)) {
2539                                 if (f) {
2540                                         ast_frfree(f);
2541                                 }
2542                                 post_manager_event("ParkedCallGiveUp", pu);
2543
2544                                 /* There's a problem, hang them up */
2545                                 ast_verb(2, "%s got tired of being parked\n", ast_channel_name(chan));
2546                                 ast_hangup(chan);
2547
2548                                 /* And take them out of the parking lot */
2549                                 return 1;
2550                         } else {
2551                                 /* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
2552                                 ast_frfree(f);
2553                                 if (pu->hold_method == AST_CONTROL_HOLD
2554                                         && pu->moh_trys < 3
2555                                         && !ast_channel_generatordata(chan)) {
2556                                         ast_debug(1,
2557                                                 "MOH on parked call stopped by outside source.  Restarting on channel %s.\n",
2558                                                 ast_channel_name(chan));
2559                                         ast_indicate_data(chan, AST_CONTROL_HOLD,
2560                                                 S_OR(pu->parkinglot->cfg.mohclass, NULL),
2561                                                 (!ast_strlen_zero(pu->parkinglot->cfg.mohclass)
2562                                                         ? strlen(pu->parkinglot->cfg.mohclass) + 1 : 0));
2563                                         pu->moh_trys++;
2564                                 }
2565                                 break;
2566                         }
2567                 } /* End for */
2568         }
2569
2570         /* mark fds for next round */
2571         for (x = 0; x < AST_MAX_FDS; x++) {
2572                 if (ast_channel_fd_isset(chan, x)) {
2573                         void *tmp = ast_realloc(*new_pfds,
2574                                 (*new_nfds + 1) * sizeof(struct pollfd));
2575
2576                         if (!tmp) {
2577                                 continue;
2578                         }
2579                         *new_pfds = tmp;
2580                         (*new_pfds)[*new_nfds].fd = ast_channel_fd(chan, x);
2581                         (*new_pfds)[*new_nfds].events = POLLIN | POLLERR | POLLPRI;
2582                         (*new_pfds)[*new_nfds].revents = 0;
2583                         (*new_nfds)++;
2584                 }
2585         }
2586         /* Keep track of our shortest wait */
2587         if (tms < *ms || *ms < 0) {
2588                 *ms = tms;
2589         }
2590
2591         /* Stay in the parking lot. */
2592         return 0;
2593 }
2594
2595 /*! \brief Run management on parkinglots, called once per parkinglot */
2596 static void manage_parkinglot(struct ast_parkinglot *curlot, const struct pollfd *pfds, int nfds, struct pollfd **new_pfds, int *new_nfds, int *ms)
2597 {
2598         struct parkeduser *pu;
2599         struct ast_context *con;
2600
2601         /* Lock parkings list */
2602         AST_LIST_LOCK(&curlot->parkings);
2603         AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
2604                 if (pu->notquiteyet) { /* Pretend this one isn't here yet */
2605                         continue;
2606                 }
2607                 if (manage_parked_call(pu, pfds, nfds, new_pfds, new_nfds, ms)) {
2608                         /* Parking is complete for this call so remove it from the parking lot. */
2609                         con = ast_context_find(pu->parkinglot->cfg.parking_con);
2610                         if (con) {
2611                                 if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0)) {
2612                                         ast_log(LOG_WARNING,
2613                                                 "Whoa, failed to remove the parking extension %s@%s!\n",
2614                                                 pu->parkingexten, pu->parkinglot->cfg.parking_con);
2615                                 }
2616                                 notify_metermaids(pu->parkingexten, pu->parkinglot->cfg.parking_con,
2617                                         AST_DEVICE_NOT_INUSE);
2618                         } else {
2619                                 ast_log(LOG_WARNING,
2620                                         "Whoa, parking lot '%s' context '%s' does not exist.\n",
2621                                         pu->parkinglot->name, pu->parkinglot->cfg.parking_con);
2622                         }
2623                         AST_LIST_REMOVE_CURRENT(list);
2624                         parkinglot_unref(pu->parkinglot);
2625                         ast_free(pu);
2626                 }
2627         }
2628         AST_LIST_TRAVERSE_SAFE_END;
2629         AST_LIST_UNLOCK(&curlot->parkings);
2630 }
2631
2632 /*!
2633  * \brief Take care of parked calls and unpark them if needed
2634  * \param ignore unused var.
2635  *
2636  * Start inf loop, lock parking lot, check if any parked channels have gone above timeout
2637  * if so, remove channel from parking lot and return it to the extension that parked it.
2638  * Check if parked channel decided to hangup, wait until next FD via select().
2639  */
2640 static void *do_parking_thread(void *ignore)
2641 {
2642         struct pollfd *pfds = NULL, *new_pfds = NULL;
2643         int nfds = 0, new_nfds = 0;
2644
2645         for (;;) {
2646                 struct ao2_iterator iter;
2647                 struct ast_parkinglot *curlot;
2648                 int ms = -1;    /* poll2 timeout, uninitialized */
2649
2650                 iter = ao2_iterator_init(parkinglots, 0);
2651                 while ((curlot = ao2_iterator_next(&iter))) {
2652                         manage_parkinglot(curlot, pfds, nfds, &new_pfds, &new_nfds, &ms);
2653                         ao2_ref(curlot, -1);
2654                 }
2655                 ao2_iterator_destroy(&iter);
2656
2657                 /* Recycle */
2658                 ast_free(pfds);
2659                 pfds = new_pfds;
2660                 nfds = new_nfds;
2661                 new_pfds = NULL;
2662                 new_nfds = 0;
2663
2664                 /* Wait for something to happen */
2665                 ast_poll(pfds, nfds, ms);
2666                 pthread_testcancel();
2667         }
2668         /* If this WERE reached, we'd need to free(pfds) */
2669         return NULL;    /* Never reached */
2670 }
2671
2672 /*! \brief Find parkinglot by name */
2673 static struct ast_parkinglot *find_parkinglot(const char *name)
2674 {
2675         struct ast_parkinglot *parkinglot;
2676
2677         if (ast_strlen_zero(name)) {
2678                 return NULL;
2679         }
2680
2681         parkinglot = ao2_find(parkinglots, (void *) name, 0);
2682         if (parkinglot) {
2683                 ast_debug(1, "Found Parking lot: %s\n", parkinglot->name);
2684         }
2685
2686         return parkinglot;
2687 }
2688
2689 /*! \brief Copy parkinglot and store it with new name */
2690 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot)
2691 {
2692         struct ast_parkinglot *copylot;
2693
2694         if ((copylot = find_parkinglot(name))) { /* Parkinglot with that name already exists */
2695                 ao2_ref(copylot, -1);
2696                 return NULL;
2697         }
2698
2699         copylot = create_parkinglot(name);
2700         if (!copylot) {
2701                 return NULL;
2702         }
2703
2704         ast_debug(1, "Building parking lot %s\n", name);
2705
2706         /* Copy the source parking lot configuration. */
2707         copylot->cfg = parkinglot->cfg;
2708
2709         return copylot;
2710 }
2711
2712 AST_APP_OPTIONS(park_call_options, BEGIN_OPTIONS
2713         AST_APP_OPTION('r', AST_PARK_OPT_RINGING),
2714         AST_APP_OPTION('R', AST_PARK_OPT_RANDOMIZE),
2715         AST_APP_OPTION('s', AST_PARK_OPT_SILENCE),
2716 END_OPTIONS );
2717
2718 /*!
2719  * \brief Unreference parkinglot object.
2720  */
2721 static void parkinglot_unref(struct ast_parkinglot *parkinglot)
2722 {
2723         ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name,
2724                 ao2_ref(parkinglot, 0) - 1);
2725         ao2_ref(parkinglot, -1);
2726 }
2727
2728 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot)
2729 {
2730         int refcount;
2731
2732         refcount = ao2_ref(parkinglot, +1);
2733         ast_debug(3, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount + 1);
2734         return parkinglot;
2735 }
2736
2737 /*! \brief Destroy a parking lot */
2738 static void parkinglot_destroy(void *obj)
2739 {
2740         struct ast_parkinglot *doomed = obj;
2741
2742         /*
2743          * No need to destroy parked calls here because any parked call
2744          * holds a parking lot reference.  Therefore the parkings list
2745          * must be empty.
2746          */
2747         ast_assert(AST_LIST_EMPTY(&doomed->parkings));
2748         AST_LIST_HEAD_DESTROY(&doomed->parkings);
2749 }
2750
2751 /*! \brief Allocate parking lot structure */
2752 static struct ast_parkinglot *create_parkinglot(const char *name)
2753 {
2754         struct ast_parkinglot *newlot;
2755
2756         if (ast_strlen_zero(name)) { /* No name specified */
2757                 return NULL;
2758         }
2759
2760         newlot = ao2_alloc(sizeof(*newlot), parkinglot_destroy);
2761         if (!newlot)
2762                 return NULL;
2763
2764         ast_copy_string(newlot->name, name, sizeof(newlot->name));
2765         newlot->cfg.is_invalid = 1;/* No config is set yet. */
2766         AST_LIST_HEAD_INIT(&newlot->parkings);
2767
2768         return newlot;
2769 }
2770
2771 /*! Default configuration for default parking lot. */
2772 static const struct parkinglot_cfg parkinglot_cfg_default_default = {
2773         .mohclass = "default",
2774         .parkext = DEFAULT_PARK_EXTENSION,
2775         .parking_con = "parkedcalls",
2776         .parking_start = 701,
2777         .parking_stop = 750,
2778         .parkingtime = DEFAULT_PARK_TIME,
2779         .comebackdialtime = DEFAULT_COMEBACK_DIAL_TIME,
2780         .comebackcontext = DEFAULT_COMEBACK_CONTEXT,
2781         .comebacktoorigin = DEFAULT_COMEBACK_TO_ORIGIN,
2782 };
2783
2784 /*! Default configuration for normal parking lots. */
2785 static const struct parkinglot_cfg parkinglot_cfg_default = {
2786         .parkext = DEFAULT_PARK_EXTENSION,
2787         .parkingtime = DEFAULT_PARK_TIME,
2788         .comebackdialtime = DEFAULT_COMEBACK_DIAL_TIME,
2789         .comebackcontext = DEFAULT_COMEBACK_CONTEXT,
2790         .comebacktoorigin = DEFAULT_COMEBACK_TO_ORIGIN,
2791 };
2792
2793 /*!
2794  * \internal
2795  * \brief Activate the given parkinglot.
2796  *
2797  * \param parkinglot Parking lot to activate.
2798  *
2799  * \details
2800  * Insert into the dialplan the context, parking lot access
2801  * extension, and optional dialplan hints.
2802  *
2803  * \retval 0 on success.
2804  * \retval -1 on error.
2805  */
2806 static int parkinglot_activate(struct ast_parkinglot *parkinglot)
2807 {
2808         /* XXX All parking stuff is being replaced by res_parking */
2809         parkinglot->disabled = 1;
2810         return -1;
2811 }
2812
2813 int ast_features_reload(void)
2814 {
2815         struct ast_context *con;
2816         int res;
2817
2818         ast_mutex_lock(&features_reload_lock);/* Searialize reloading features.conf */
2819
2820         /*
2821          * Always destroy the parking_con_dial context to remove buildup
2822          * of recalled extensions in the context.  At worst, the parked
2823          * call gets hungup attempting to run an invalid extension when
2824          * we are trying to callback the parker or the preset return
2825          * extension.  This is a small window of opportunity on an
2826          * execution chain that is not expected to happen very often.
2827          */
2828         con = ast_context_find(parking_con_dial);
2829         if (con) {
2830                 ast_context_destroy(con, registrar);
2831         }
2832
2833         res = ast_features_config_reload();
2834         ast_mutex_unlock(&features_reload_lock);
2835
2836         return res;
2837 }
2838
2839 static char *handle_features_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2840 {
2841         switch (cmd) {
2842         case CLI_INIT:
2843                 e->command = "features reload";
2844                 e->usage =
2845                         "Usage: features reload\n"
2846                         "       Reloads configured call features from features.conf\n";
2847                 return NULL;
2848         case CLI_GENERATE:
2849                 return NULL;
2850         }
2851         ast_features_reload();
2852
2853         return CLI_SUCCESS;
2854 }
2855
2856 enum play_tone_action {
2857         PLAYTONE_NONE = 0,
2858         PLAYTONE_CHANNEL1 = (1 << 0),
2859         PLAYTONE_CHANNEL2 = (1 << 1),
2860         PLAYTONE_BOTH = PLAYTONE_CHANNEL1 | PLAYTONE_CHANNEL2,
2861 };
2862
2863 static enum play_tone_action parse_playtone(const char *playtone_val)
2864 {
2865         if (ast_strlen_zero(playtone_val) || ast_false(playtone_val)) {
2866                 return PLAYTONE_NONE;
2867         } if (!strcasecmp(playtone_val, "channel1")) {
2868                 return PLAYTONE_CHANNEL1;
2869         } else if (!strcasecmp(playtone_val, "channel2") || ast_true(playtone_val)) {
2870                 return PLAYTONE_CHANNEL2;
2871         } else if (!strcasecmp(playtone_val, "both")) {
2872                 return PLAYTONE_BOTH;
2873         } else {
2874                 /* Invalid input. Assume none */
2875                 return PLAYTONE_NONE;
2876         }
2877 }
2878
2879 /*!
2880  * \brief Bridge channels together
2881  * \param s
2882  * \param m
2883  *
2884  * Make sure valid channels were specified,
2885  * send errors if any of the channels could not be found/locked, answer channels if needed,
2886  * create the placeholder channels and grab the other channels
2887  * make the channels compatible, send error if we fail doing so
2888  * setup the bridge thread object and start the bridge.
2889  *
2890  * \retval 0
2891  */
2892 static int action_bridge(struct mansession *s, const struct message *m)
2893 {
2894         const char *channela = astman_get_header(m, "Channel1");
2895         const char *channelb = astman_get_header(m, "Channel2");
2896         enum play_tone_action playtone = parse_playtone(astman_get_header(m, "Tone"));
2897         RAII_VAR(struct ast_channel *, chana, NULL, ao2_cleanup);
2898         RAII_VAR(struct ast_channel *, chanb, NULL, ao2_cleanup);
2899         const char *chana_name;
2900         const char *chana_exten;
2901         const char *chana_context;
2902         int chana_priority;
2903         const char *chanb_name;
2904         const char *chanb_exten;
2905         const char *chanb_context;
2906         int chanb_priority;
2907         struct ast_bridge *bridge;
2908         char buf[256];
2909         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_a, NULL, ao2_cleanup);
2910         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_b, NULL, ao2_cleanup);
2911
2912         /* make sure valid channels were specified */
2913         if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
2914                 astman_send_error(s, m, "Missing channel parameter in request");
2915                 return 0;
2916         }
2917
2918         /* Start with chana */
2919         chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
2920         if (!chana) {
2921                 snprintf(buf, sizeof(buf), "Channel1 does not exist: %s", channela);
2922                 astman_send_error(s, m, buf);
2923                 return 0;
2924         }
2925         xfer_cfg_a = ast_get_chan_features_xfer_config(chana);
2926         ast_channel_lock(chana);
2927         chana_name = ast_strdupa(ast_channel_name(chana));
2928         chana_exten = ast_strdupa(ast_channel_exten(chana));
2929         chana_context = ast_strdupa(ast_channel_context(chana));
2930         chana_priority = ast_channel_priority(chana);
2931         if (!ast_test_flag(ast_channel_flags(chana), AST_FLAG_IN_AUTOLOOP)) {
2932                 chana_priority++;
2933         }
2934         ast_channel_unlock(chana);
2935
2936         chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
2937         if (!chanb) {
2938                 snprintf(buf, sizeof(buf), "Channel2 does not exist: %s", channelb);
2939                 astman_send_error(s, m, buf);
2940                 return 0;
2941         }
2942         xfer_cfg_b = ast_get_chan_features_xfer_config(chanb);
2943         ast_channel_lock(chanb);
2944         chanb_name = ast_strdupa(ast_channel_name(chanb));
2945         chanb_exten = ast_strdupa(ast_channel_exten(chanb));
2946         chanb_context = ast_strdupa(ast_channel_context(chanb));
2947         chanb_priority = ast_channel_priority(chanb);
2948         if (!ast_test_flag(ast_channel_flags(chanb), AST_FLAG_IN_AUTOLOOP)) {
2949                 chanb_priority++;
2950         }
2951         ast_channel_unlock(chanb);
2952
2953         bridge = ast_bridge_basic_new();
2954         if (!bridge) {
2955                 astman_send_error(s, m, "Unable to create bridge\n");
2956                 return 0;
2957         }
2958
2959         ast_bridge_set_after_go_on(chana, chana_context, chana_exten, chana_priority, NULL);
2960         if (ast_bridge_add_channel(bridge, chana, NULL, playtone & PLAYTONE_CHANNEL1, xfer_cfg_a ? xfer_cfg_a->xfersound : NULL)) {
2961                 snprintf(buf, sizeof(buf), "Unable to add Channel1 to bridge: %s", ast_channel_name(chana));
2962                 astman_send_error(s, m, buf);
2963                 ast_bridge_destroy(bridge);
2964                 return 0;
2965         }
2966
2967         ast_bridge_set_after_go_on(chanb, chanb_context, chanb_exten, chanb_priority, NULL);
2968         if (ast_bridge_add_channel(bridge, chanb, NULL, playtone & PLAYTONE_CHANNEL2, xfer_cfg_b ? xfer_cfg_b->xfersound : NULL)) {
2969                 snprintf(buf, sizeof(buf), "Unable to add Channel2 to bridge: %s", ast_channel_name(chanb));
2970                 astman_send_error(s, m, buf);
2971                 ast_bridge_destroy(bridge);
2972                 return 0;
2973         }
2974
2975         /*** DOCUMENTATION
2976                 <managerEventInstance>
2977                         <synopsis>Raised when a bridge is successfully created due to a manager action.</synopsis>
2978                         <syntax>
2979                                 <parameter name="Response">
2980                                         <enumlist>
2981                                                 <enum name="Success"/>
2982                                                 <enum name="Failed"/>
2983                                         </enumlist>
2984                                 </parameter>
2985                         </syntax>
2986                         <see-also>
2987                                 <ref type="manager">Bridge</ref>
2988                         </see-also>
2989                 </managerEventInstance>
2990         ***/
2991 /* BUGBUG This event used to use ast_manager_event_multichan. Now channel variables are not included in the event */
2992         manager_event(EVENT_FLAG_CALL, "BridgeAction",
2993                                 "Response: Success\r\n"
2994                                 "Channel1: %s\r\n"
2995                                 "Channel2: %s\r\n", chana_name, chanb_name);
2996
2997         astman_send_ack(s, m, "Channels have been bridged");
2998
2999         return 0;
3000 }
3001
3002 static struct ast_cli_entry cli_features[] = {
3003         AST_CLI_DEFINE(handle_features_reload, "Reloads configured features"),
3004 };
3005
3006 /*!
3007  * The presence of this datastore on the channel indicates that
3008  * someone is attemting to pickup or has picked up the channel.
3009  * The purpose is to prevent a race between two channels
3010  * attempting to pickup the same channel.
3011  */
3012 static const struct ast_datastore_info pickup_active = {
3013         .type = "pickup-active",
3014 };
3015
3016 int ast_can_pickup(struct ast_channel *chan)
3017 {
3018         if (!ast_channel_pbx(chan) && !ast_channel_masq(chan) && !ast_test_flag(ast_channel_flags(chan), AST_FLAG_ZOMBIE)
3019                 && (ast_channel_state(chan) == AST_STATE_RINGING
3020                         || ast_channel_state(chan) == AST_STATE_RING
3021                         /*
3022                          * Check the down state as well because some SIP devices do not
3023                          * give 180 ringing when they can just give 183 session progress
3024                          * instead.  Issue 14005.  (Some ISDN switches as well for that
3025                          * matter.)
3026                          */
3027                         || ast_channel_state(chan) == AST_STATE_DOWN)
3028                 && !ast_channel_datastore_find(chan, &pickup_active, NULL)) {
3029                 return 1;
3030         }
3031         return 0;
3032 }
3033
3034 static int find_channel_by_group(void *obj, void *arg, void *data, int flags)
3035 {
3036         struct ast_channel *target = obj;/*!< Potential pickup target */
3037         struct ast_channel *chan = arg;/*!< Channel wanting to pickup call */
3038
3039         if (chan == target) {
3040                 return 0;
3041         }
3042
3043         ast_channel_lock(target);
3044         if (ast_can_pickup(target)) {
3045                 /* Lock both channels. */
3046                 while (ast_channel_trylock(chan)) {
3047                         ast_channel_unlock(target);
3048                         sched_yield();
3049                         ast_channel_lock(target);
3050                 }
3051
3052                 /*
3053                  * Both callgroup and namedcallgroup pickup variants are
3054                  * matched independently.  Checking for named group match is
3055                  * done last since it's a more expensive operation.
3056                  */
3057                 if ((ast_channel_pickupgroup(chan) & ast_channel_callgroup(target))
3058                         || (ast_namedgroups_intersect(ast_channel_named_pickupgroups(chan),
3059                                 ast_channel_named_callgroups(target)))) {
3060                         struct ao2_container *candidates = data;/*!< Candidate channels found. */
3061
3062                         /* This is a candidate to pickup */
3063                         ao2_link(candidates, target);
3064                 }
3065                 ast_channel_unlock(chan);
3066         }
3067         ast_channel_unlock(target);
3068
3069         return 0;
3070 }
3071
3072 struct ast_channel *ast_pickup_find_by_group(struct ast_channel *chan)
3073 {
3074         struct ao2_container *candidates;/*!< Candidate channels found to pickup. */
3075         struct ast_channel *target;/*!< Potential pickup target */
3076
3077         candidates = ao2_container_alloc_options(AO2_ALLOC_OPT_LOCK_NOLOCK, 1, NULL, NULL);
3078         if (!candidates) {
3079                 return NULL;
3080         }
3081
3082         /* Find all candidate targets by group. */
3083         ast_channel_callback(find_channel_by_group, chan, candidates, 0);
3084
3085         /* Find the oldest pickup target candidate */
3086         target = NULL;
3087         for (;;) {
3088                 struct ast_channel *candidate;/*!< Potential new older target */
3089                 struct ao2_iterator iter;
3090
3091                 iter = ao2_iterator_init(candidates, 0);
3092                 while ((candidate = ao2_iterator_next(&iter))) {
3093                         if (!target) {
3094                                 /* First target. */
3095                                 target = candidate;
3096                                 continue;
3097                         }
3098                         if (ast_tvcmp(ast_channel_creationtime(candidate), ast_channel_creationtime(target)) < 0) {
3099                                 /* We have a new target. */
3100                                 ast_channel_unref(target);
3101                                 target = candidate;
3102                                 continue;
3103                         }
3104                         ast_channel_unref(candidate);
3105                 }
3106                 ao2_iterator_destroy(&iter);
3107                 if (!target) {
3108                         /* No candidates found. */
3109                         break;
3110                 }
3111
3112                 /* The found channel must be locked and ref'd. */
3113                 ast_channel_lock(target);
3114
3115                 /* Recheck pickup ability */
3116                 if (ast_can_pickup(target)) {
3117                         /* This is the channel to pickup. */
3118                         break;
3119                 }
3120
3121                 /* Someone else picked it up or the call went away. */
3122                 ast_channel_unlock(target);
3123                 ao2_unlink(candidates, target);
3124                 target = ast_channel_unref(target);
3125         }
3126         ao2_ref(candidates, -1);
3127
3128         return target;
3129 }
3130
3131 /*!
3132  * \brief Pickup a call
3133  * \param chan channel that initiated pickup.
3134  *
3135  * Walk list of channels, checking it is not itself, channel is pbx one,
3136  * check that the callgroup for both channels are the same and the channel is ringing.
3137  * Answer calling channel, flag channel as answered on queue, masq channels together.
3138  */
3139 int ast_pickup_call(struct ast_channel *chan)
3140 {
3141         struct ast_channel *target;/*!< Potential pickup target */
3142         int res = -1;
3143         RAII_VAR(struct ast_features_pickup_config *, pickup_cfg, NULL, ao2_cleanup);
3144         const char *pickup_sound;
3145         const char *fail_sound;
3146
3147         ast_debug(1, "pickup attempt by %s\n", ast_channel_name(chan));
3148         ast_channel_lock(chan);
3149         pickup_cfg = ast_get_chan_features_pickup_config(chan);
3150         if (!pickup_cfg) {
3151                 ast_log(LOG_ERROR, "Unable to retrieve pickup configuration. Unable to play pickup sounds\n");
3152         }
3153         pickup_sound = ast_strdupa(pickup_cfg ? pickup_cfg->pickupsound : "");
3154         fail_sound = ast_strdupa(pickup_cfg ? pickup_cfg->pickupfailsound : "");
3155         ast_channel_unlock(chan);
3156
3157         /* The found channel is already locked. */
3158         target = ast_pickup_find_by_group(chan);
3159         if (target) {
3160                 ast_log(LOG_NOTICE, "pickup %s attempt by %s\n", ast_channel_name(target), ast_channel_name(chan));
3161
3162                 res = ast_do_pickup(chan, target);
3163                 ast_channel_unlock(target);
3164                 if (!res) {
3165                         if (!ast_strlen_zero(pickup_sound)) {
3166                                 pbx_builtin_setvar_helper(target, "BRIDGE_PLAY_SOUND", pickup_sound);
3167                         }
3168                 } else {
3169                         ast_log(LOG_WARNING, "pickup %s failed by %s\n", ast_channel_name(target), ast_channel_name(chan));
3170                 }
3171                 target = ast_channel_unref(target);
3172         }
3173
3174         if (res < 0) {
3175                 ast_debug(1, "No call pickup possible... for %s\n", ast_channel_name(chan));
3176                 if (!ast_strlen_zero(fail_sound)) {
3177                         ast_answer(chan);
3178                         ast_stream_and_wait(chan, fail_sound, "");
3179                 }
3180         }
3181
3182         return res;
3183 }
3184
3185 static struct ast_manager_event_blob *call_pickup_to_ami(struct stasis_message *message)
3186 {
3187         struct ast_multi_channel_blob *contents = stasis_message_data(message);
3188         struct ast_channel_snapshot *chan;
3189         struct ast_channel_snapshot *target;
3190         struct ast_manager_event_blob *res;
3191
3192         RAII_VAR(struct ast_str *, channel_str, NULL, ast_free);
3193         RAII_VAR(struct ast_str *, target_str, NULL, ast_free);
3194
3195         chan = ast_multi_channel_blob_get_channel(contents, "channel");
3196         target = ast_multi_channel_blob_get_channel(contents, "target");
3197
3198         ast_assert(chan != NULL && target != NULL);
3199
3200         if (!(channel_str = ast_manager_build_channel_state_string(chan))) {
3201                 return NULL;
3202         }
3203
3204         if (!(target_str = ast_manager_build_channel_state_string_prefix(target, "Target"))) {
3205                 return NULL;
3206         }
3207
3208         res = ast_manager_event_blob_create(EVENT_FLAG_CALL, "Pickup",
3209                 "%s"
3210                 "%s",
3211                 ast_str_buffer(channel_str),
3212                 ast_str_buffer(target_str));
3213
3214         return res;
3215 }
3216
3217 static int send_call_pickup_stasis_message(struct ast_channel *picking_up, struct ast_channel_snapshot *chan, struct ast_channel_snapshot *target)
3218 {
3219         RAII_VAR(struct ast_multi_channel_blob *, pickup_payload, NULL, ao2_cleanup);
3220         RAII_VAR(struct stasis_message *, msg, NULL, ao2_cleanup);
3221
3222         if (!(pickup_payload = ast_multi_channel_blob_create(ast_json_null()))) {
3223                 return -1;
3224         }
3225
3226         ast_multi_channel_blob_add_channel(pickup_payload, "channel", chan);
3227         ast_multi_channel_blob_add_channel(pickup_payload, "target", target);
3228
3229         if (!(msg = stasis_message_create(ast_call_pickup_type(), pickup_payload))) {
3230                 return -1;
3231         }
3232
3233         stasis_publish(ast_channel_topic(picking_up), msg);
3234         return 0;
3235 }
3236
3237 int ast_do_pickup(struct ast_channel *chan, struct ast_channel *target)
3238 {
3239         struct ast_party_connected_line connected_caller;
3240         struct ast_datastore *ds_pickup;
3241         const char *chan_name;/*!< A masquerade changes channel names. */
3242         const char *target_name;/*!< A masquerade changes channel names. */
3243         int res = -1;
3244
3245         RAII_VAR(struct ast_channel_snapshot *, chan_snapshot, NULL, ao2_cleanup);
3246         RAII_VAR(struct ast_channel_snapshot *, target_snapshot, NULL, ao2_cleanup);
3247
3248         target_name = ast_strdupa(ast_channel_name(target));
3249         ast_debug(1, "Call pickup on '%s' by '%s'\n", target_name, ast_channel_name(chan));
3250
3251         /* Mark the target to block any call pickup race. */
3252         ds_pickup = ast_datastore_alloc(&pickup_active, NULL);
3253         if (!ds_pickup) {
3254                 ast_log(LOG_WARNING,
3255                         "Unable to create channel datastore on '%s' for call pickup\n", target_name);
3256                 return -1;
3257         }
3258         ast_channel_datastore_add(target, ds_pickup);
3259
3260         ast_party_connected_line_init(&connected_caller);
3261         ast_party_connected_line_copy(&connected_caller, ast_channel_connected(target));
3262         ast_channel_unlock(target);/* The pickup race is avoided so we do not need the lock anymore. */
3263         /* Reset any earlier private connected id representation */
3264         ast_party_id_reset(&connected_caller.priv);
3265
3266         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
3267         if (ast_channel_connected_line_sub(NULL, chan, &connected_caller, 0) &&
3268                 ast_channel_connected_line_macro(NULL, chan, &connected_caller, 0, 0)) {
3269                 ast_channel_update_connected_line(chan, &connected_caller, NULL);
3270         }
3271         ast_party_connected_line_free(&connected_caller);
3272
3273         ast_channel_lock(chan);
3274         chan_name = ast_strdupa(ast_channel_name(chan));
3275         ast_connected_line_copy_from_caller(&connected_caller, ast_channel_caller(chan));
3276         ast_channel_unlock(chan);
3277         connected_caller.source = AST_CONNECTED_LINE_UPDATE_SOURCE_ANSWER;
3278
3279         if (ast_answer(chan)) {
3280                 ast_log(LOG_WARNING, "Unable to answer '%s'\n", chan_name);
3281                 goto pickup_failed;
3282         }
3283
3284         if (ast_queue_control(chan, AST_CONTROL_ANSWER)) {
3285                 ast_log(LOG_WARNING, "Unable to queue answer on '%s'\n", chan_name);
3286                 goto pickup_failed;
3287         }
3288
3289         ast_channel_queue_connected_line_update(chan, &connected_caller, NULL);
3290
3291         /* setting the HANGUPCAUSE so the ringing channel knows this call was not a missed call */
3292         ast_channel_hangupcause_set(chan, AST_CAUSE_ANSWERED_ELSEWHERE);
3293
3294         if (!(chan_snapshot = ast_channel_snapshot_create(chan))) {
3295                 goto pickup_failed;
3296         }
3297
3298         if (!(target_snapshot = ast_channel_snapshot_create(target))) {
3299                 goto pickup_failed;
3300         }
3301
3302         if (ast_channel_move(target, chan)) {
3303                 ast_log(LOG_WARNING, "Unable to masquerade '%s' into '%s'\n", chan_name,
3304                         target_name);
3305                 goto pickup_failed;
3306         }
3307
3308         /* target points to the channel that did the pickup at this point, so use that channel's topic instead of chan */
3309         send_call_pickup_stasis_message(target, chan_snapshot, target_snapshot);
3310
3311         res = 0;
3312
3313 pickup_failed:
3314         ast_channel_lock(target);
3315         if (!ast_channel_datastore_remove(target, ds_pickup)) {
3316                 ast_datastore_free(ds_pickup);
3317         }
3318         ast_party_connected_line_free(&connected_caller);
3319
3320         return res;
3321 }
3322
3323 static char *app_bridge = "Bridge";
3324
3325 enum {
3326         BRIDGE_OPT_PLAYTONE = (1 << 0),
3327         OPT_CALLEE_HANGUP =     (1 << 1),
3328         OPT_CALLER_HANGUP =     (1 << 2),
3329         OPT_DURATION_LIMIT = (1 << 3),
3330         OPT_DURATION_STOP =     (1 << 4),
3331         OPT_CALLEE_TRANSFER = (1 << 5),
3332         OPT_CALLER_TRANSFER = (1 << 6),
3333         OPT_CALLEE_MONITOR = (1 << 7),
3334         OPT_CALLER_MONITOR = (1 << 8),
3335         OPT_CALLEE_PARK = (1 << 9),
3336         OPT_CALLER_PARK = (1 << 10),
3337         OPT_CALLEE_KILL = (1 << 11),
3338         OPT_CALLEE_GO_ON = (1 << 12),
3339 };
3340
3341 enum {
3342         OPT_ARG_DURATION_LIMIT = 0,
3343         OPT_ARG_DURATION_STOP,
3344         OPT_ARG_CALLEE_GO_ON,
3345         /* note: this entry _MUST_ be the last one in the enum */
3346         OPT_ARG_ARRAY_SIZE,
3347 };
3348
3349 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
3350         AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
3351         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
3352         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
3353         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
3354         AST_APP_OPTION('k', OPT_CALLEE_PARK),
3355         AST_APP_OPTION('K', OPT_CALLER_PARK),
3356         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
3357         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
3358         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
3359         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
3360         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
3361         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
3362         AST_APP_OPTION('x', OPT_CALLEE_KILL),
3363 END_OPTIONS );
3364
3365 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
3366         char *parse, struct timeval *calldurationlimit)
3367 {
3368         char *stringp = ast_strdupa(parse);
3369         char *limit_str, *warning_str, *warnfreq_str;
3370         const char *var;
3371         int play_to_caller = 0, play_to_callee = 0;
3372         int delta;
3373
3374         limit_str = strsep(&stringp, ":");
3375         warning_str = strsep(&stringp, ":");
3376         warnfreq_str = strsep(&stringp, ":");
3377
3378         config->timelimit = atol(limit_str);
3379         if (warning_str)
3380                 config->play_warning = atol(warning_str);
3381         if (warnfreq_str)
3382                 config->warning_freq = atol(warnfreq_str);
3383
3384         if (!config->timelimit) {
3385                 ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
3386                 config->timelimit = config->play_warning = config->warning_freq = 0;
3387                 config->warning_sound = NULL;
3388                 return -1; /* error */
3389         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
3390                 int w = config->warning_freq;
3391
3392                 /*
3393                  * If the first warning is requested _after_ the entire call
3394                  * would end, and no warning frequency is requested, then turn
3395                  * off the warning. If a warning frequency is requested, reduce
3396                  * the 'first warning' time by that frequency until it falls
3397                  * within the call's total time limit.
3398                  *
3399                  * Graphically:
3400                  *                timelim->|    delta        |<-playwarning
3401                  *      0__________________|_________________|
3402                  *                       | w  |    |    |    |
3403                  *
3404                  * so the number of intervals to cut is 1+(delta-1)/w
3405                  */
3406                 if (w == 0) {
3407                         config->play_warning = 0;
3408                 } else {
3409                         config->play_warning -= w * ( 1 + (delta-1)/w );
3410                         if (config->play_warning < 1)
3411                                 config->play_warning = config->warning_freq = 0;
3412                 }
3413         }
3414
3415         ast_channel_lock(chan);
3416
3417         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
3418         play_to_caller = var ? ast_true(var) : 1;
3419
3420         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
3421         play_to_callee = var ? ast_true(var) : 0;
3422
3423         if (!play_to_caller && !play_to_callee)
3424                 play_to_caller = 1;
3425
3426         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
3427         config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
3428
3429         /* The code looking at config wants a NULL, not just "", to decide
3430          * that the message should not be played, so we replace "" with NULL.
3431          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
3432          * not found.
3433          */
3434
3435         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
3436         config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
3437
3438         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
3439         config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
3440
3441         ast_channel_unlock(chan);
3442
3443         /* undo effect of S(x) in case they are both used */
3444         calldurationlimit->tv_sec = 0;
3445         calldurationlimit->tv_usec = 0;
3446
3447         /* more efficient to do it like S(x) does since no advanced opts */
3448         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
3449                 calldurationlimit->tv_sec = config->timelimit / 1000;
3450                 calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
3451                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
3452                         calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
3453                 play_to_caller = 0;
3454                 play_to_callee = 0;
3455                 config->timelimit = 0;
3456                 config->play_warning = 0;
3457                 config->warning_freq = 0;
3458         } else {
3459                 ast_verb(4, "Limit Data for this call:\n");
3460                 ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
3461                 ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
3462                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
3463                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
3464                 ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
3465                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
3466                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
3467                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
3468         }
3469         if (play_to_caller)
3470                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
3471         if (play_to_callee)
3472                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
3473         return 0;
3474 }
3475
3476
3477 /*!
3478  * \brief Bridge channels
3479  * \param chan
3480  * \param data channel to bridge with.
3481  *
3482  * Split data, check we aren't bridging with ourself, check valid channel,
3483  * answer call if not already, check compatible channels, setup bridge config
3484  * now bridge call, if transfered party hangs up return to PBX extension.
3485  */
3486 static int bridge_exec(struct ast_channel *chan, const char *data)
3487 {
3488         RAII_VAR(struct ast_channel *, current_dest_chan, NULL, ao2_cleanup);
3489         struct ast_channel *chans[2];
3490         char *tmp_data  = NULL;
3491         struct ast_flags opts = { 0, };
3492         struct ast_bridge_config bconfig = { { 0, }, };
3493         char *opt_args[OPT_ARG_ARRAY_SIZE];
3494         struct timeval calldurationlimit = { 0, };
3495         const char *context;
3496         const char *extension;
3497         int priority;
3498         struct ast_bridge_features chan_features;
3499         struct ast_bridge_features *peer_features;
3500         struct ast_bridge *bridge;
3501         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
3502
3503         AST_DECLARE_APP_ARGS(args,
3504                 AST_APP_ARG(dest_chan);
3505                 AST_APP_ARG(options);
3506         );
3507
3508         if (ast_strlen_zero(data)) {
3509                 ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
3510                 return -1;
3511         }
3512
3513         tmp_data = ast_strdupa(data);
3514         AST_STANDARD_APP_ARGS(args, tmp_data);
3515         if (!ast_strlen_zero(args.options))
3516                 ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
3517
3518         /* make sure we have a valid end point */
3519         if (!(current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
3520                         strlen(args.dest_chan)))) {
3521                 ast_log(LOG_WARNING, "Bridge failed because channel %s does not exist\n",
3522                         args.dest_chan);
3523                 ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
3524                         "Response: Failed\r\n"
3525                         "Reason: Channel2 does not exist\r\n"
3526                         "Channel1: %s\r\n"
3527                         "Channel2: %s\r\n", ast_channel_name(chan), args.dest_chan);
3528                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "NONEXISTENT");
3529                 return 0;
3530         }
3531
3532         /* avoid bridge with ourselves */
3533         if (chan == current_dest_chan) {
3534                 ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", ast_channel_name(chan));
3535                 /*** DOCUMENTATION
3536                         <managerEventInstance>
3537                                 <synopsis>Raised when an error occurs during bridge creation.</synopsis>
3538                                 <see-also>
3539                                         <ref type="application">Bridge</ref>
3540                                 </see-also>
3541                         </managerEventInstance>
3542                 ***/
3543                 ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
3544                         "Response: Failed\r\n"
3545                         "Reason: Unable to bridge channel to itself\r\n"
3546                         "Channel1: %s\r\n"
3547                         "Channel2: %s\r\n",
3548                         ast_channel_name(chan), args.dest_chan);
3549                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "LOOP");
3550                 return 0;
3551         }
3552
3553         if (ast_test_flag(&opts, OPT_DURATION_LIMIT)
3554                 && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])
3555                 && ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit)) {
3556                 ast_manager_event(chan, EVENT_FLAG_CALL, "BridgeExec",
3557                         "Response: Failed\r\n"
3558                         "Reason: Cannot setup bridge time limit\r\n"
3559                         "Channel1: %s\r\n"
3560                         "Channel2: %s\r\n", ast_channel_name(chan), args.dest_chan);
3561                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
3562                 goto done;
3563         }
3564
3565         chans[0] = chan;
3566         chans[1] = current_dest_chan;
3567
3568         /* Report that the bridge will be successfull */
3569         /*** DOCUMENTATION
3570                 <managerEventInstance>
3571                         <synopsis>Raised when the bridge is created successfully.</synopsis>
3572                         <see-also>
3573                                 <ref type="application">Bridge</ref>
3574                         </see-also>
3575                 </managerEventInstance>
3576         ***/
3577         ast_manager_event_multichan(EVENT_FLAG_CALL, "BridgeExec", 2, chans,
3578                 "Response: Success\r\n"
3579                 "Channel1: %s\r\n"
3580                 "Channel2: %s\r\n", ast_channel_name(chan), ast_channel_name(current_dest_chan));
3581
3582         if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
3583                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
3584         if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
3585                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
3586         if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
3587                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
3588         if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
3589                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
3590         if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
3591                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
3592         if (ast_test_flag(&opts, OPT_CALLER_MONITOR))
3593                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
3594         if (ast_test_flag(&opts, OPT_CALLEE_PARK))
3595                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
3596         if (ast_test_flag(&opts, OPT_CALLER_PARK))
3597                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCAL