Remove status_response callbacks where they are not needed.
[asterisk/asterisk.git] / main / features.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Routines implementing call features as call pickup, parking and transfer
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31
32 #include <pthread.h>
33 #include <signal.h>
34 #include <sys/time.h>
35 #include <sys/signal.h>
36 #include <netinet/in.h>
37
38 #include "asterisk/lock.h"
39 #include "asterisk/file.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/causes.h"
43 #include "asterisk/module.h"
44 #include "asterisk/translate.h"
45 #include "asterisk/app.h"
46 #include "asterisk/say.h"
47 #include "asterisk/features.h"
48 #include "asterisk/musiconhold.h"
49 #include "asterisk/config.h"
50 #include "asterisk/cli.h"
51 #include "asterisk/manager.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/adsi.h"
54 #include "asterisk/devicestate.h"
55 #include "asterisk/monitor.h"
56 #include "asterisk/audiohook.h"
57 #include "asterisk/global_datastores.h"
58 #include "asterisk/astobj2.h"
59 #include "asterisk/cel.h"
60 #include "asterisk/test.h"
61
62 /*** DOCUMENTATION
63         <application name="Bridge" language="en_US">
64                 <synopsis>
65                         Bridge two channels.
66                 </synopsis>
67                 <syntax>
68                         <parameter name="channel" required="true">
69                                 <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
70                         </parameter>
71                         <parameter name="options">
72                                 <optionlist>
73                                         <option name="p">
74                                                 <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
75                                         </option>
76                                         <option name="h">
77                                                 <para>Allow the called party to hang up by sending the
78                                                 <replaceable>*</replaceable> DTMF digit.</para>
79                                         </option>
80                                         <option name="H">
81                                                 <para>Allow the calling party to hang up by pressing the
82                                                 <replaceable>*</replaceable> DTMF digit.</para>
83                                         </option>
84                                         <option name="k">
85                                                 <para>Allow the called party to enable parking of the call by sending
86                                                 the DTMF sequence defined for call parking in features.conf.</para>
87                                         </option>
88                                         <option name="K">
89                                                 <para>Allow the calling party to enable parking of the call by sending
90                                                  the DTMF sequence defined for call parking in features.conf.</para>
91                                         </option>
92                                         <option name="L(x[:y][:z])">
93                                                 <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
94                                                 when <replaceable>y</replaceable> ms are left. Repeat the warning every
95                                                 <replaceable>z</replaceable> ms. The following special variables can be
96                                                 used with this option:</para>
97                                                 <variablelist>
98                                                         <variable name="LIMIT_PLAYAUDIO_CALLER">
99                                                                 <para>Play sounds to the caller. yes|no (default yes)</para>
100                                                         </variable>
101                                                         <variable name="LIMIT_PLAYAUDIO_CALLEE">   
102                                                                 <para>Play sounds to the callee. yes|no</para>
103                                                         </variable>
104                                                         <variable name="LIMIT_TIMEOUT_FILE">
105                                                                 <para>File to play when time is up.</para>
106                                                         </variable>
107                                                         <variable name="LIMIT_CONNECT_FILE">
108                                                                 <para>File to play when call begins.</para>
109                                                         </variable>
110                                                         <variable name="LIMIT_WARNING_FILE">
111                                                                 <para>File to play as warning if <replaceable>y</replaceable> is
112                                                                 defined. The default is to say the time remaining.</para>
113                                                         </variable>
114                                                 </variablelist>
115                                         </option>
116                                         <option name="S(x)">
117                                                 <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
118                                         </option>
119                                         <option name="t">
120                                                 <para>Allow the called party to transfer the calling party by sending the
121                                                 DTMF sequence defined in features.conf.</para>
122                                         </option>
123                                         <option name="T">
124                                                 <para>Allow the calling party to transfer the called party by sending the
125                                                 DTMF sequence defined in features.conf.</para>
126                                         </option>
127                                         <option name="w">
128                                                 <para>Allow the called party to enable recording of the call by sending
129                                                 the DTMF sequence defined for one-touch recording in features.conf.</para>
130                                         </option>
131                                         <option name="W">
132                                                 <para>Allow the calling party to enable recording of the call by sending
133                                                 the DTMF sequence defined for one-touch recording in features.conf.</para>
134                                         </option>
135                                         <option name="x">
136                                                 <para>Cause the called party to be hung up after the bridge, instead of being
137                                                 restarted in the dialplan.</para>
138                                         </option>
139                                 </optionlist>
140                         </parameter>
141                 </syntax>
142                 <description>
143                         <para>Allows the ability to bridge two channels via the dialplan.</para>
144                         <para>This application sets the following channel variable upon completion:</para>
145                         <variablelist>
146                                 <variable name="BRIDGERESULT">
147                                         <para>The result of the bridge attempt as a text string.</para>
148                                         <value name="SUCCESS" />
149                                         <value name="FAILURE" />
150                                         <value name="LOOP" />
151                                         <value name="NONEXISTENT" />
152                                         <value name="INCOMPATIBLE" />
153                                 </variable>
154                         </variablelist>
155                 </description>
156         </application>
157         <application name="ParkedCall" language="en_US">
158                 <synopsis>
159                         Answer a parked call.
160                 </synopsis>
161                 <syntax>
162                         <parameter name="exten" required="true" />
163                 </syntax>
164                 <description>
165                         <para>Used to connect to a parked call. This application is always
166                         registered internally and does not need to be explicitly added
167                         into the dialplan, although you should include the <literal>parkedcalls</literal>
168                         context. If no extension is provided, then the first available
169                         parked call will be acquired.</para>
170                 </description>
171                 <see-also>
172                         <ref type="application">Park</ref>
173                         <ref type="application">ParkAndAnnounce</ref>
174                 </see-also>
175         </application>
176         <application name="Park" language="en_US">
177                 <synopsis>
178                         Park yourself.
179                 </synopsis>
180                 <syntax>
181                         <parameter name="timeout">
182                                 <para>A custom parking timeout for this parked call.</para>
183                         </parameter>
184                         <parameter name="return_context">
185                                 <para>The context to return the call to after it times out.</para>
186                         </parameter>
187                         <parameter name="return_exten">
188                                 <para>The extension to return the call to after it times out.</para>
189                         </parameter>
190                         <parameter name="return_priority">
191                                 <para>The priority to return the call to after it times out.</para>
192                         </parameter>
193                         <parameter name="options">
194                                 <para>A list of options for this parked call.</para>
195                                 <optionlist>
196                                         <option name="r">
197                                                 <para>Send ringing instead of MOH to the parked call.</para>
198                                         </option>
199                                         <option name="R">
200                                                 <para>Randomize the selection of a parking space.</para>
201                                         </option>
202                                         <option name="s">
203                                                 <para>Silence announcement of the parking space number.</para>
204                                         </option>
205                                 </optionlist>
206                         </parameter>
207                 </syntax>
208                 <description>
209                         <para>Used to park yourself (typically in combination with a supervised
210                         transfer to know the parking space). This application is always
211                         registered internally and does not need to be explicitly added
212                         into the dialplan, although you should include the <literal>parkedcalls</literal>
213                         context (or the context specified in <filename>features.conf</filename>).</para>
214                         <para>If you set the <variable>PARKINGLOT</variable> variable, the call will be parked
215                         in the specifed parking context. Note setting this variable overrides the <variable>
216                         PARKINGLOT</variable> set by the <literal>CHANNEL</literal> function.</para>
217                         <para>If you set the <variable>PARKINGEXTEN</variable> variable to an extension in your
218                         parking context, Park() will park the call on that extension, unless
219                         it already exists. In that case, execution will continue at next priority.</para>
220                         <para>If you set the <variable>PARKINGLOT</variable> variable, Park() will park the call
221                         in that parkinglot.</para>
222                         <para>If you set the <variable>PARKINGDYNAMIC</variable> variable, this parkinglot from features.conf
223                         will be used as template for the newly created dynamic lot.</para>
224                         <para>If you set the <variable>PARKINGDYNCONTEXT</variable> variable the newly created dynamic
225                         parking lot will use this context.</para>
226                         <para>If you set the <variable>PARKINGDYNPOS</variable> variable the newly created dynamic parkinglot
227                         will use those parking postitions.</para>
228                 </description>
229                 <see-also>
230                         <ref type="application">ParkAndAnnounce</ref>
231                         <ref type="application">ParkedCall</ref>
232                 </see-also>
233         </application>
234         <manager name="ParkedCalls" language="en_US">
235                 <synopsis>
236                         List parked calls.
237                 </synopsis>
238                 <syntax>
239                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
240                 </syntax>
241                 <description>
242                         <para>List parked calls.</para>
243                 </description>
244         </manager>
245         <manager name="Park" language="en_US">
246                 <synopsis>
247                         Park a channel.
248                 </synopsis>
249                 <syntax>
250                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
251                         <parameter name="Channel" required="true">
252                                 <para>Channel name to park.</para>
253                         </parameter>
254                         <parameter name="Channel2" required="true">
255                                 <para>Channel to announce park info to (and return to if timeout).</para>
256                         </parameter>
257                         <parameter name="Timeout">
258                                 <para>Number of milliseconds to wait before callback.</para>
259                         </parameter>
260                 </syntax>
261                 <description>
262                         <para>Park a channel.</para>
263                 </description>
264         </manager>
265         <manager name="Bridge" language="en_US">
266                 <synopsis>
267                         Bridge two channels already in the PBX.
268                 </synopsis>
269                 <syntax>
270                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
271                         <parameter name="Channel1" required="true">
272                                 <para>Channel to Bridge to Channel2.</para>
273                         </parameter>
274                         <parameter name="Channel2" required="true">
275                                 <para>Channel to Bridge to Channel1.</para>
276                         </parameter>
277                         <parameter name="Tone">
278                                 <para>Play courtesy tone to Channel 2.</para>
279                                 <enumlist>
280                                         <enum name="yes" />
281                                         <enum name="no" />
282                                 </enumlist>
283                         </parameter>
284                 </syntax>
285                 <description>
286                         <para>Bridge together two channels already in the PBX.</para>
287                 </description>
288         </manager>
289  ***/
290
291 #define DEFAULT_PARK_TIME 45000
292 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
293 #define DEFAULT_FEATURE_DIGIT_TIMEOUT 1000
294 #define DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER 15000
295 #define DEFAULT_PARKINGLOT "default"                    /*!< Default parking lot */
296 #define DEFAULT_ATXFER_DROP_CALL 0
297 #define DEFAULT_ATXFER_LOOP_DELAY 10000
298 #define DEFAULT_ATXFER_CALLBACK_RETRIES 2
299
300 #define AST_MAX_WATCHERS 256
301 #define MAX_DIAL_FEATURE_OPTIONS 30
302
303 struct feature_group_exten {
304         AST_LIST_ENTRY(feature_group_exten) entry;
305         AST_DECLARE_STRING_FIELDS(
306                 AST_STRING_FIELD(exten);
307         );
308         struct ast_call_feature *feature;
309 };
310
311 struct feature_group {
312         AST_LIST_ENTRY(feature_group) entry;
313         AST_DECLARE_STRING_FIELDS(
314                 AST_STRING_FIELD(gname);
315         );
316         AST_LIST_HEAD_NOLOCK(, feature_group_exten) features;
317 };
318
319 static AST_RWLIST_HEAD_STATIC(feature_groups, feature_group);
320
321 static char *parkedcall = "ParkedCall";
322
323 static char pickup_ext[AST_MAX_EXTENSION];                 /*!< Call pickup extension */
324
325 /*! \brief Description of one parked call, added to a list while active, then removed.
326         The list belongs to a parkinglot 
327 */
328 struct parkeduser {
329         struct ast_channel *chan;                   /*!< Parking channel */
330         struct timeval start;                       /*!< Time the parking started */
331         int parkingnum;                             /*!< Parking lot */
332         char parkingexten[AST_MAX_EXTENSION];       /*!< If set beforehand, parking extension used for this call */
333         char context[AST_MAX_CONTEXT];              /*!< Where to go if our parking time expires */
334         char exten[AST_MAX_EXTENSION];
335         int priority;
336         int parkingtime;                            /*!< Maximum length in parking lot before return */
337         unsigned int notquiteyet:1;
338         unsigned int options_specified:1;
339         char peername[1024];
340         unsigned char moh_trys;
341         struct ast_parkinglot *parkinglot;
342         AST_LIST_ENTRY(parkeduser) list;
343 };
344
345 /*! \brief Structure for parking lots which are put in a container. */
346 struct ast_parkinglot {
347         char name[AST_MAX_CONTEXT];
348         char parking_con[AST_MAX_EXTENSION];            /*!< Context for which parking is made accessible */
349         char parking_con_dial[AST_MAX_EXTENSION];       /*!< Context for dialback for parking (KLUDGE) */
350         int parking_start;                              /*!< First available extension for parking */
351         int parking_stop;                               /*!< Last available extension for parking */
352         int parking_offset;
353         int parkfindnext;
354         int parkingtime;                                /*!< Default parking time */
355         char mohclass[MAX_MUSICCLASS];                  /*!< Music class used for parking */
356         int parkaddhints;                               /*!< Add parking hints automatically */
357         int parkedcalltransfers;                        /*!< Enable DTMF based transfers on bridge when picking up parked calls */
358         int parkedcallreparking;                        /*!< Enable DTMF based parking on bridge when picking up parked calls */
359         int parkedcallhangup;                           /*!< Enable DTMF based hangup on a bridge when pickup up parked calls */
360         int parkedcallrecording;                        /*!< Enable DTMF based recording on a bridge when picking up parked calls */
361         AST_LIST_HEAD(parkinglot_parklist, parkeduser) parkings; /*!< List of active parkings in this parkinglot */
362 };
363
364 /*! \brief The list of parking lots configured. Always at least one  - the default parking lot */
365 static struct ao2_container *parkinglots;
366  
367 struct ast_parkinglot *default_parkinglot;
368 char parking_ext[AST_MAX_EXTENSION];            /*!< Extension you type to park the call */
369
370 static char courtesytone[256];                             /*!< Courtesy tone */
371 static int parkedplay = 0;                                 /*!< Who to play the courtesy tone to */
372 static int parkeddynamic = 0;                              /*!< Enable creation of parkinglots dynamically */
373 static char xfersound[256];                                /*!< Call transfer sound */
374 static char xferfailsound[256];                            /*!< Call transfer failure sound */
375 static char pickupsound[256];                              /*!< Pickup sound */
376 static char pickupfailsound[256];                          /*!< Pickup failure sound */
377
378 static int adsipark;
379
380 static int transferdigittimeout;
381 static int featuredigittimeout;
382 static int comebacktoorigin = 1;
383
384 static int atxfernoanswertimeout;
385 static unsigned int atxferdropcall;
386 static unsigned int atxferloopdelay;
387 static unsigned int atxfercallbackretries;
388
389 static char *registrar = "features";               /*!< Registrar for operations */
390
391 /* module and CLI command definitions */
392 static char *parkcall = PARK_APP_NAME;
393
394 static struct ast_app *monitor_app = NULL;
395 static int monitor_ok = 1;
396
397 static struct ast_app *mixmonitor_app = NULL;
398 static int mixmonitor_ok = 1;
399
400 static struct ast_app *stopmixmonitor_app = NULL;
401 static int stopmixmonitor_ok = 1;
402
403 static pthread_t parking_thread;
404 struct ast_dial_features {
405         struct ast_flags features_caller;
406         struct ast_flags features_callee;
407         int is_caller;
408 };
409
410 static void *dial_features_duplicate(void *data)
411 {
412         struct ast_dial_features *df = data, *df_copy;
413  
414         if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
415                 return NULL;
416         }
417  
418         memcpy(df_copy, df, sizeof(*df));
419  
420         return df_copy;
421 }
422
423 static void dial_features_destroy(void *data)
424 {
425         struct ast_dial_features *df = data;
426         if (df) {
427                 ast_free(df);
428         }
429 }
430
431 static const struct ast_datastore_info dial_features_info = {
432         .type = "dial-features",
433         .destroy = dial_features_destroy,
434         .duplicate = dial_features_duplicate,
435  };
436  
437 /* Forward declarations */
438 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot);
439 static void parkinglot_unref(struct ast_parkinglot *parkinglot);
440 static void parkinglot_destroy(void *obj);
441 int manage_parkinglot(struct ast_parkinglot *curlot, fd_set *rfds, fd_set *efds, fd_set *nrfds, fd_set *nefds, int *fs, int *max);
442 struct ast_parkinglot *find_parkinglot(const char *name);
443 static struct ast_parkinglot *create_parkinglot(const char *name);
444 static struct ast_parkinglot *copy_parkinglot(const char *name, const struct ast_parkinglot *parkinglot);
445
446 const char *ast_parking_ext(void)
447 {
448         return parking_ext;
449 }
450
451 const char *ast_pickup_ext(void)
452 {
453         return pickup_ext;
454 }
455
456 struct ast_bridge_thread_obj 
457 {
458         struct ast_bridge_config bconfig;
459         struct ast_channel *chan;
460         struct ast_channel *peer;
461         unsigned int return_to_pbx:1;
462 };
463
464 static int parkinglot_hash_cb(const void *obj, const int flags)
465 {
466         const struct ast_parkinglot *parkinglot = obj;
467
468         return ast_str_case_hash(parkinglot->name);
469 }
470
471 static int parkinglot_cmp_cb(void *obj, void *arg, int flags)
472 {
473         struct ast_parkinglot *parkinglot = obj, *parkinglot2 = arg;
474
475         return !strcasecmp(parkinglot->name, parkinglot2->name) ? CMP_MATCH | CMP_STOP : 0;
476 }
477
478 /*!
479  * \brief store context, extension and priority 
480  * \param chan, context, ext, pri
481 */
482 static void set_c_e_p(struct ast_channel *chan, const char *context, const char *ext, int pri)
483 {
484         ast_copy_string(chan->context, context, sizeof(chan->context));
485         ast_copy_string(chan->exten, ext, sizeof(chan->exten));
486         chan->priority = pri;
487 }
488
489 /*!
490  * \brief Check goto on transfer
491  * \param chan
492  *
493  * Check if channel has 'GOTO_ON_BLINDXFR' set, if not exit.
494  * When found make sure the types are compatible. Check if channel is valid
495  * if so start the new channel else hangup the call. 
496 */
497 static void check_goto_on_transfer(struct ast_channel *chan) 
498 {
499         struct ast_channel *xferchan;
500         const char *val = pbx_builtin_getvar_helper(chan, "GOTO_ON_BLINDXFR");
501         char *x, *goto_on_transfer;
502         struct ast_frame *f;
503
504         if (ast_strlen_zero(val))
505                 return;
506
507         goto_on_transfer = ast_strdupa(val);
508
509         if (!(xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", chan->linkedid, 0, "%s", chan->name)))
510                 return;
511
512         for (x = goto_on_transfer; x && *x; x++) {
513                 if (*x == '^')
514                         *x = '|';
515         }
516         /* Make formats okay */
517         xferchan->readformat = chan->readformat;
518         xferchan->writeformat = chan->writeformat;
519         ast_channel_masquerade(xferchan, chan);
520         ast_parseable_goto(xferchan, goto_on_transfer);
521         xferchan->_state = AST_STATE_UP;
522         ast_clear_flag(xferchan, AST_FLAGS_ALL);        
523         xferchan->_softhangup = 0;
524         if ((f = ast_read(xferchan))) {
525                 ast_frfree(f);
526                 f = NULL;
527                 ast_pbx_start(xferchan);
528         } else {
529                 ast_hangup(xferchan);
530         }
531 }
532
533 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller, struct ast_channel *transferee, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, int igncallerstate, const char *language);
534
535 /*!
536  * \brief bridge the call 
537  * \param data thread bridge.
538  *
539  * Set Last Data for respective channels, reset cdr for channels
540  * bridge call, check if we're going back to dialplan
541  * if not hangup both legs of the call
542 */
543 static void *bridge_call_thread(void *data)
544 {
545         struct ast_bridge_thread_obj *tobj = data;
546         int res;
547
548         tobj->chan->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
549         tobj->chan->data = tobj->peer->name;
550         tobj->peer->appl = !tobj->return_to_pbx ? "Transferred Call" : "ManagerBridge";
551         tobj->peer->data = tobj->chan->name;
552
553         ast_bridge_call(tobj->peer, tobj->chan, &tobj->bconfig);
554
555         if (tobj->return_to_pbx) {
556                 if (!ast_check_hangup(tobj->peer)) {
557                         ast_log(LOG_VERBOSE, "putting peer %s into PBX again\n", tobj->peer->name);
558                         res = ast_pbx_start(tobj->peer);
559                         if (res != AST_PBX_SUCCESS)
560                                 ast_log(LOG_WARNING, "FAILED continuing PBX on peer %s\n", tobj->peer->name);
561                 } else
562                         ast_hangup(tobj->peer);
563                 if (!ast_check_hangup(tobj->chan)) {
564                         ast_log(LOG_VERBOSE, "putting chan %s into PBX again\n", tobj->chan->name);
565                         res = ast_pbx_start(tobj->chan);
566                         if (res != AST_PBX_SUCCESS)
567                                 ast_log(LOG_WARNING, "FAILED continuing PBX on chan %s\n", tobj->chan->name);
568                 } else
569                         ast_hangup(tobj->chan);
570         } else {
571                 ast_hangup(tobj->chan);
572                 ast_hangup(tobj->peer);
573         }
574
575         ast_free(tobj);
576
577         return NULL;
578 }
579
580 /*!
581  * \brief create thread for the parked call
582  * \param data
583  *
584  * Create thread and attributes, call bridge_call_thread
585 */
586 static void bridge_call_thread_launch(void *data) 
587 {
588         pthread_t thread;
589         pthread_attr_t attr;
590         struct sched_param sched;
591
592         pthread_attr_init(&attr);
593         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
594         ast_pthread_create(&thread, &attr, bridge_call_thread, data);
595         pthread_attr_destroy(&attr);
596         memset(&sched, 0, sizeof(sched));
597         pthread_setschedparam(thread, SCHED_RR, &sched);
598 }
599
600 /*!
601  * \brief Announce call parking by ADSI
602  * \param chan .
603  * \param parkingexten .
604  * Create message to show for ADSI, display message.
605  * \retval 0 on success.
606  * \retval -1 on failure.
607 */
608 static int adsi_announce_park(struct ast_channel *chan, char *parkingexten)
609 {
610         int res;
611         int justify[5] = {ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT, ADSI_JUST_CENT};
612         char tmp[256];
613         char *message[5] = {NULL, NULL, NULL, NULL, NULL};
614
615         snprintf(tmp, sizeof(tmp), "Parked on %s", parkingexten);
616         message[0] = tmp;
617         res = ast_adsi_load_session(chan, NULL, 0, 1);
618         if (res == -1)
619                 return res;
620         return ast_adsi_print(chan, message, justify, 1);
621 }
622
623 /*! \brief Find parking lot name from channel */
624 static const char *findparkinglotname(struct ast_channel *chan)
625 {
626         const char *temp, *parkinglot = NULL;
627
628         /* Check if the channel has a parking lot */
629         if (!ast_strlen_zero(chan->parkinglot))
630                 parkinglot = chan->parkinglot;
631
632         /* Channel variables override everything */
633
634         if ((temp  = pbx_builtin_getvar_helper(chan, "PARKINGLOT")))
635                 return temp;
636
637         return parkinglot;
638 }
639
640 /*! \brief Notify metermaids that we've changed an extension */
641 static void notify_metermaids(const char *exten, char *context, enum ast_device_state state)
642 {
643         ast_debug(4, "Notification of state change to metermaids %s@%s\n to state '%s'", 
644                 exten, context, ast_devstate2str(state));
645
646         ast_devstate_changed(state, "park:%s@%s", exten, context);
647 }
648
649 /*! \brief metermaids callback from devicestate.c */
650 static enum ast_device_state metermaidstate(const char *data)
651 {
652         char *context;
653         char *exten;
654
655         context = ast_strdupa(data);
656
657         exten = strsep(&context, "@");
658         if (!context)
659                 return AST_DEVICE_INVALID;
660         
661         ast_debug(4, "Checking state of exten %s in context %s\n", exten, context);
662
663         if (!ast_exists_extension(NULL, context, exten, 1, NULL))
664                 return AST_DEVICE_NOT_INUSE;
665
666         return AST_DEVICE_INUSE;
667 }
668
669 /*! Options to pass to park_call_full */
670 enum ast_park_call_options {
671         /*! Provide ringing to the parked caller instead of music on hold */
672         AST_PARK_OPT_RINGING =   (1 << 0),
673         /*! Randomly choose a parking spot for the caller instead of choosing
674          *  the first one that is available. */
675         AST_PARK_OPT_RANDOMIZE = (1 << 1),
676         /*! Do not announce the parking number */
677         AST_PARK_OPT_SILENCE = (1 << 2),
678 };
679
680 struct ast_park_call_args {
681         /*! How long to wait in the parking lot before the call gets sent back
682          *  to the specified return extension (or a best guess at where it came
683          *  from if not explicitly specified). */
684         int timeout;
685         /*! An output parameter to store the parking space where the parked caller
686          *  was placed. */
687         int *extout;
688         const char *orig_chan_name;
689         const char *return_con;
690         const char *return_ext;
691         int return_pri;
692         uint32_t flags;
693         /*! Parked user that has already obtained a parking space */
694         struct parkeduser *pu;
695 };
696
697 static struct parkeduser *park_space_reserve(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
698 {
699         struct parkeduser *pu;
700         int i, parking_space = -1, parking_range;
701         const char *parkinglotname = NULL;
702         const char *parkingexten;
703         struct ast_parkinglot *parkinglot = NULL;
704
705         if (peer)
706                 parkinglotname = findparkinglotname(peer);
707         else /* peer was NULL, check chan (ParkAndAnnounce / res_agi) */
708                 parkinglotname = findparkinglotname(chan);
709
710         if (parkinglotname) {
711                 ast_debug(1, "Found chanvar Parkinglot: %s\n", parkinglotname);
712                 parkinglot = find_parkinglot(parkinglotname);
713
714         }
715
716         /* Dynamically create parkinglot */
717         if (!parkinglot && parkeddynamic && !ast_strlen_zero(parkinglotname)) {
718                 const char *dyn_context, *dyn_range;
719                 const char *parkinglotname_copy = NULL;
720                 struct ast_parkinglot *parkinglot_copy = NULL;
721                 int dyn_start, dyn_end;
722
723                 ast_channel_lock(chan);
724                 parkinglotname_copy = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNAMIC"), ""));
725                 dyn_context = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNCONTEXT"), ""));
726                 dyn_range = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGDYNPOS"), ""));
727                 ast_channel_unlock(chan);
728
729                 if (!ast_strlen_zero(parkinglotname_copy)) {
730                         parkinglot_copy = find_parkinglot(parkinglotname_copy);
731                 }
732                 if (!parkinglot_copy) {
733                         parkinglot_copy = parkinglot_addref(default_parkinglot);
734                         ast_debug(1, "Using default parking lot for copy\n");
735                 }
736                 if (!(parkinglot = copy_parkinglot(parkinglotname, parkinglot_copy))) {
737                         ast_log(LOG_ERROR, "Could not build dynamic parking lot!\n");
738                 } else {
739                         if (!ast_strlen_zero(dyn_context)) {
740                                 ast_copy_string(parkinglot->parking_con, dyn_context, sizeof(parkinglot->parking_con));
741                         }
742                         if (!ast_strlen_zero(dyn_range)) {
743                                 if (sscanf(dyn_range, "%30d-%30d", &dyn_start, &dyn_end) != 2) {
744                                         ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers\n");
745                                 } else {
746                                         parkinglot->parking_start = dyn_start;
747                                         parkinglot->parking_stop = dyn_end;
748                                 }
749                         }
750                         ao2_link(parkinglots, parkinglot);
751                 }
752
753                 if (parkinglot_copy) {
754                         /* unref our tempory copy */
755                         parkinglot_unref(parkinglot_copy);
756                         parkinglot_copy = NULL;
757                 }
758         }
759
760         if (!parkinglot) {
761                 parkinglot = parkinglot_addref(default_parkinglot);
762         }
763
764         if (option_debug)
765                 ast_log(LOG_DEBUG, "Parkinglot: %s\n", parkinglot->name);
766
767         /* Allocate memory for parking data */
768         if (!(pu = ast_calloc(1, sizeof(*pu)))) {
769                 parkinglot_unref(parkinglot);
770                 return NULL;
771         }
772
773         /* Lock parking list */
774         AST_LIST_LOCK(&parkinglot->parkings);
775         /* Check for channel variable PARKINGEXTEN */
776         ast_channel_lock(chan);
777         parkingexten = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "PARKINGEXTEN"), ""));
778         ast_channel_unlock(chan);
779         if (!ast_strlen_zero(parkingexten)) {
780                 /*!\note The API forces us to specify a numeric parking slot, even
781                  * though the architecture would tend to support non-numeric extensions
782                  * (as are possible with SIP, for example).  Hence, we enforce that
783                  * limitation here.  If extout was not numeric, we could permit
784                  * arbitrary non-numeric extensions.
785                  */
786         if (sscanf(parkingexten, "%30d", &parking_space) != 1 || parking_space < 0) {
787                         AST_LIST_UNLOCK(&parkinglot->parkings);
788                         parkinglot_unref(parkinglot);
789             free(pu);
790             ast_log(LOG_WARNING, "PARKINGEXTEN does not indicate a valid parking slot: '%s'.\n", parkingexten);
791             return NULL;
792         }
793         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
794
795                 if (ast_exists_extension(NULL, parkinglot->parking_con, pu->parkingexten, 1, NULL)) {
796                         ast_log(LOG_WARNING, "Requested parking extension already exists: %s@%s\n", parkingexten, parkinglot->parking_con);
797                         AST_LIST_UNLOCK(&parkinglot->parkings);
798                         parkinglot_unref(parkinglot);
799                         ast_free(pu);
800                         return NULL;
801                 }
802         } else {
803                 int start;
804                 struct parkeduser *cur = NULL;
805
806                 /* Select parking space within range */
807                 parking_range = parkinglot->parking_stop - parkinglot->parking_start + 1;
808
809                 if (ast_test_flag(args, AST_PARK_OPT_RANDOMIZE)) {
810                         start = ast_random() % (parkinglot->parking_stop - parkinglot->parking_start + 1);
811                 } else {
812                         start = parkinglot->parking_start;
813                 }
814
815                 for (i = start; 1; i++) {
816                         if (i == parkinglot->parking_stop + 1) {
817                                 i = parkinglot->parking_start - 1;
818                                 break;
819                         }
820
821                         AST_LIST_TRAVERSE(&parkinglot->parkings, cur, list) {
822                                 if (cur->parkingnum == i) {
823                                         break;
824                                 }
825                         }
826                         if (!cur) {
827                                 parking_space = i;
828                                 break;
829                         }
830                 }
831
832                 if (i == start - 1 && cur) {
833                         ast_log(LOG_WARNING, "No more parking spaces\n");
834                         ast_free(pu);
835                         AST_LIST_UNLOCK(&parkinglot->parkings);
836                         parkinglot_unref(parkinglot);
837                         return NULL;
838                 }
839                 /* Set pointer for next parking */
840                 if (parkinglot->parkfindnext) 
841                         parkinglot->parking_offset = parking_space - parkinglot->parking_start + 1;
842                 snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", parking_space);
843         }
844
845         pu->notquiteyet = 1;
846         pu->parkingnum = parking_space;
847         pu->parkinglot = parkinglot_addref(parkinglot);
848         AST_LIST_INSERT_TAIL(&parkinglot->parkings, pu, list);
849         parkinglot_unref(parkinglot);
850
851         return pu;
852 }
853
854 /* Park a call */
855 static int park_call_full(struct ast_channel *chan, struct ast_channel *peer, struct ast_park_call_args *args)
856 {
857         struct ast_context *con;
858         int parkingnum_copy;
859         struct parkeduser *pu = args->pu;
860         const char *event_from;
861
862         if (pu == NULL)
863                 args->pu = pu = park_space_reserve(chan, peer, args);
864         if (pu == NULL)
865                 return 1; /* Continue execution if possible */
866
867         snprintf(pu->parkingexten, sizeof(pu->parkingexten), "%d", pu->parkingnum);
868
869         chan->appl = "Parked Call";
870         chan->data = NULL;
871
872         pu->chan = chan;
873
874         /* Put the parked channel on hold if we have two different channels */
875         if (chan != peer) {
876                 if (ast_test_flag(args, AST_PARK_OPT_RINGING)) {
877                         ast_indicate(pu->chan, AST_CONTROL_RINGING);
878                 } else {
879                         ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
880                                 S_OR(pu->parkinglot->mohclass, NULL),
881                                 !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
882                 }
883         }
884         
885         pu->start = ast_tvnow();
886         pu->parkingtime = (args->timeout > 0) ? args->timeout : pu->parkinglot->parkingtime;
887         parkingnum_copy = pu->parkingnum;
888         if (args->extout)
889                 *(args->extout) = pu->parkingnum;
890
891         if (peer) { 
892                 /* This is so ugly that it hurts, but implementing get_base_channel() on local channels
893                         could have ugly side effects.  We could have transferer<->local,1<->local,2<->parking
894                         and we need the callback name to be that of transferer.  Since local,1/2 have the same
895                         name we can be tricky and just grab the bridged channel from the other side of the local
896                 */
897                 if (!strcasecmp(peer->tech->type, "Local")) {
898                         struct ast_channel *tmpchan, *base_peer;
899                         char other_side[AST_CHANNEL_NAME];
900                         char *c;
901                         ast_copy_string(other_side, S_OR(args->orig_chan_name, peer->name), sizeof(other_side));
902                         if ((c = strrchr(other_side, ';'))) {
903                                 *++c = '1';
904                         }
905                         if ((tmpchan = ast_channel_get_by_name(other_side))) {
906                                 ast_channel_lock(tmpchan);
907                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
908                                         ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
909                                 }
910                                 ast_channel_unlock(tmpchan);
911                                 tmpchan = ast_channel_unref(tmpchan);
912                         }
913                 } else {
914                         ast_copy_string(pu->peername, S_OR(args->orig_chan_name, peer->name), sizeof(pu->peername));
915                 }
916         }
917
918         /* Remember what had been dialed, so that if the parking
919            expires, we try to come back to the same place */
920
921         pu->options_specified = (!ast_strlen_zero(args->return_con) || !ast_strlen_zero(args->return_ext) || args->return_pri);
922
923         /* If extension has options specified, they override all other possibilities
924         such as the returntoorigin flag and transferred context. Information on
925         extension options is lost here, so we set a flag */
926
927         ast_copy_string(pu->context, 
928                 S_OR(args->return_con, S_OR(chan->macrocontext, chan->context)), 
929                 sizeof(pu->context));
930         ast_copy_string(pu->exten, 
931                 S_OR(args->return_ext, S_OR(chan->macroexten, chan->exten)), 
932                 sizeof(pu->exten));
933         pu->priority = args->return_pri ? args->return_pri : 
934                 (chan->macropriority ? chan->macropriority : chan->priority);
935
936         /* If parking a channel directly, don't quiet yet get parking running on it.
937          * All parking lot entries are put into the parking lot with notquiteyet on. */
938         if (peer != chan) 
939                 pu->notquiteyet = 0;
940
941         /* Wake up the (presumably select()ing) thread */
942         pthread_kill(parking_thread, SIGURG);
943         ast_verb(2, "Parked %s on %d (lot %s). Will timeout back to extension [%s] %s, %d in %d seconds\n", pu->chan->name, pu->parkingnum, pu->parkinglot->name, pu->context, pu->exten, pu->priority, (pu->parkingtime/1000));
944
945         ast_cel_report_event(pu->chan, AST_CEL_PARK_START, NULL, pu->parkinglot->name, peer);
946
947         if (peer) {
948                 event_from = peer->name;
949         } else {
950                 event_from = pbx_builtin_getvar_helper(chan, "BLINDTRANSFER");
951         }
952
953         ast_manager_event(pu->chan, EVENT_FLAG_CALL, "ParkedCall",
954                 "Exten: %s\r\n"
955                 "Channel: %s\r\n"
956                 "Parkinglot: %s\r\n"
957                 "From: %s\r\n"
958                 "Timeout: %ld\r\n"
959                 "CallerIDNum: %s\r\n"
960                 "CallerIDName: %s\r\n"
961                 "Uniqueid: %s\r\n",
962                 pu->parkingexten, pu->chan->name, pu->parkinglot->name, event_from ? event_from : "",
963                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
964                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
965                 S_OR(pu->chan->cid.cid_name, "<unknown>"),
966                 pu->chan->uniqueid
967                 );
968
969         if (peer && adsipark && ast_adsi_available(peer)) {
970                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
971                 ast_adsi_unload_session(peer);
972         }
973
974         con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con, registrar);
975         if (!con)       /* Still no context? Bad */
976                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con);
977         if (con) {
978                 if (!ast_add_extension2(con, 1, pu->parkingexten, 1, NULL, NULL, parkedcall, ast_strdup(pu->parkingexten), ast_free_ptr, registrar))
979                         notify_metermaids(pu->parkingexten, pu->parkinglot->parking_con, AST_DEVICE_INUSE);
980         }
981
982         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
983
984         /* Only say number if it's a number and the channel hasn't been masqueraded away */
985         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE) && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(peer->name, args->orig_chan_name))) {
986                 /* If a channel is masqueraded into peer while playing back the parking slot number do not continue playing it back. This is the case if an attended transfer occurs. */
987                 ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
988                 /* Tell the peer channel the number of the parking space */
989                 ast_say_digits(peer, pu->parkingnum, "", peer->language);
990                 ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
991         }
992         if (peer == chan) { /* pu->notquiteyet = 1 */
993                 /* Wake up parking thread if we're really done */
994                 ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
995                         S_OR(pu->parkinglot->mohclass, NULL),
996                         !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
997                 pu->notquiteyet = 0;
998                 pthread_kill(parking_thread, SIGURG);
999         }
1000         return 0;
1001 }
1002
1003 /*! \brief Park a call */
1004 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout)
1005 {
1006         struct ast_park_call_args args = {
1007                 .timeout = timeout,
1008                 .extout = extout,
1009         };
1010
1011         return park_call_full(chan, peer, &args);
1012 }
1013
1014 static int masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout, int play_announcement, struct ast_park_call_args *args)
1015 {
1016         struct ast_channel *chan;
1017         struct ast_frame *f;
1018         int park_status;
1019         struct ast_park_call_args park_args = {0,};
1020
1021         if (!args) {
1022                 args = &park_args;
1023                 args->timeout = timeout;
1024                 args->extout = extout;
1025         }
1026
1027         if ((args->pu = park_space_reserve(rchan, peer, args)) == NULL) {
1028                 if (peer)
1029                         ast_stream_and_wait(peer, "beeperr", "");
1030                 return AST_FEATURE_RETURN_PARKFAILED;
1031         }
1032
1033         /* Make a new, fake channel that we'll use to masquerade in the real one */
1034         if (!(chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, rchan->accountcode, rchan->exten, rchan->context, rchan->linkedid, rchan->amaflags, "Parked/%s",rchan->name))) {
1035                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
1036                 return -1;
1037         }
1038
1039         /* Make formats okay */
1040         chan->readformat = rchan->readformat;
1041         chan->writeformat = rchan->writeformat;
1042         ast_channel_masquerade(chan, rchan);
1043
1044         /* Setup the extensions and such */
1045         set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
1046
1047         /* Setup the macro extension and such */
1048         ast_copy_string(chan->macrocontext,rchan->macrocontext,sizeof(chan->macrocontext));
1049         ast_copy_string(chan->macroexten,rchan->macroexten,sizeof(chan->macroexten));
1050         chan->macropriority = rchan->macropriority;
1051
1052         /* Make the masq execute */
1053         if ((f = ast_read(chan)))
1054                 ast_frfree(f);
1055
1056         if (peer == rchan) {
1057                 peer = chan;
1058         }
1059
1060         if (peer && (!play_announcement && args == &park_args)) {
1061                 args->orig_chan_name = ast_strdupa(peer->name);
1062         }
1063
1064         park_status = park_call_full(chan, peer, args);
1065         if (park_status == 1) {
1066         /* would be nice to play "invalid parking extension" */
1067                 ast_hangup(chan);
1068                 return -1;
1069         }
1070
1071         return 0;
1072 }
1073
1074 /* Park call via masqueraded channel */
1075 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1076 {
1077         return masq_park_call(rchan, peer, timeout, extout, 0, NULL);
1078 }
1079
1080 static int masq_park_call_announce_args(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
1081 {
1082         return masq_park_call(rchan, peer, 0, NULL, 1, args);
1083 }
1084
1085 static int masq_park_call_announce(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
1086 {
1087         return masq_park_call(rchan, peer, timeout, extout, 1, NULL);
1088 }
1089
1090 #ifdef TEST_FRAMEWORK
1091 static int fake_fixup(struct ast_channel *clonechan, struct ast_channel *original)
1092 {
1093         return 0;
1094 }
1095
1096 static struct ast_channel *create_test_channel(const struct ast_channel_tech *fake_tech)
1097 {
1098         struct ast_channel *test_channel1;
1099         if (!(test_channel1 = ast_channel_alloc(0, AST_STATE_DOWN, NULL, NULL, NULL,
1100         NULL, NULL, 0, 0, "TestChannel1"))) {
1101                 return NULL;
1102         }
1103
1104         /* normally this is done in the channel driver */
1105         test_channel1->nativeformats = AST_FORMAT_GSM;
1106         test_channel1->writeformat = AST_FORMAT_GSM;
1107         test_channel1->rawwriteformat = AST_FORMAT_GSM;
1108         test_channel1->readformat = AST_FORMAT_GSM;
1109         test_channel1->rawreadformat = AST_FORMAT_GSM;
1110         test_channel1->tech = fake_tech;
1111
1112         return test_channel1;
1113 }
1114
1115 static int unpark_test_channel(struct ast_channel *toremove, struct ast_park_call_args *args)
1116 {
1117         struct ast_context *con;
1118         struct parkeduser *pu_toremove;
1119         args->pu->notquiteyet = 1; /* go ahead and stop processing the test parking */
1120         AST_LIST_LOCK(&args->pu->parkinglot->parkings);
1121         AST_LIST_TRAVERSE_SAFE_BEGIN(&args->pu->parkinglot->parkings, pu_toremove, list) {
1122                 con = ast_context_find(args->pu->parkinglot->parking_con);
1123                 if (con) {
1124                         if (ast_context_remove_extension2(con, args->pu->parkingexten, 1, NULL, 0)) {
1125                                 ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
1126                                 return -1;
1127                         } else {
1128                                 notify_metermaids(args->pu->parkingexten, pu_toremove->parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
1129                         }
1130                 } else {
1131                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
1132                         return -1;
1133                 }
1134                 if (pu_toremove == args->pu) {
1135                         AST_LIST_REMOVE_CURRENT(list);
1136                         break;
1137                 }
1138         }
1139         AST_LIST_TRAVERSE_SAFE_END;
1140         AST_LIST_UNLOCK(&args->pu->parkinglot->parkings);
1141
1142         /* the only way this would be unsafe is if a timeout occurred, which is set at 45 sec */
1143         ast_free(args->pu);
1144         args->pu = NULL;
1145
1146         ast_hangup(toremove);
1147         return 0;
1148 }
1149
1150 AST_TEST_DEFINE(features_test)
1151 {
1152         int saved_parkeddynamic;
1153         struct ast_channel *test_channel1 = NULL;
1154         struct ast_channel *parked_chan = NULL;
1155         struct ast_parkinglot *dynlot = NULL;
1156         struct ast_park_call_args args = {
1157                 .timeout = DEFAULT_PARK_TIME,
1158         };
1159
1160         int res = -1;
1161
1162         static const struct ast_channel_tech fake_tech = {
1163                 .fixup = fake_fixup, /* silence warning from masquerade */
1164         };
1165
1166         static const char unique_parkinglot[] = "myuniquetestparkinglot3141592654";
1167         static const char parkinglot_range[] = "750-760";
1168
1169         switch (cmd) {
1170         case TEST_INIT:
1171                 info->name = "features_test";
1172                 info->category = "main/features/";
1173                 info->summary = "Features unit test";
1174                 info->description =
1175                         "Tests whether parking respects PARKINGLOT settings";
1176                 return AST_TEST_NOT_RUN;
1177         case TEST_EXECUTE:
1178                 break;
1179         }
1180
1181         /* changing a config option is a bad practice, but must be done in this case */
1182         saved_parkeddynamic = parkeddynamic;
1183         parkeddynamic = 1;
1184
1185         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1186                 goto exit_features_test;
1187         }
1188
1189         ast_test_status_update(test, "Test parking functionality with defaults\n");
1190         if (park_call_full(test_channel1, NULL, &args)) {
1191                 goto exit_features_test;
1192         }
1193         if (unpark_test_channel(test_channel1, &args)) {
1194                 goto exit_features_test;
1195         }
1196
1197         ast_test_status_update(test, "Check that certain parking options are respected\n");
1198         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1199                 goto exit_features_test;
1200         }
1201         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1202         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1203         if (park_call_full(test_channel1, NULL, &args)) {
1204                 goto exit_features_test;
1205         }
1206         /* grab newly created parking lot for destruction in the end */
1207         dynlot = args.pu->parkinglot;
1208         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1209                 ast_test_status_update(test, "Parking settings were not respected\n");
1210                 goto exit_features_test;
1211         } else {
1212                 ast_test_status_update(test, "Parking settings for non-masquerading park verified\n");
1213         }
1214         if (unpark_test_channel(test_channel1, &args)) {
1215                 goto exit_features_test;
1216         }
1217
1218         ast_test_status_update(test, "Check #2 that certain parking options are respected\n");
1219         if (!(test_channel1 = create_test_channel(&fake_tech))) {
1220                 goto exit_features_test;
1221         }
1222         pbx_builtin_setvar_helper(test_channel1, "PARKINGLOT", unique_parkinglot);
1223         pbx_builtin_setvar_helper(test_channel1, "PARKINGDYNPOS", parkinglot_range);
1224         if (masq_park_call(test_channel1, NULL, 0, NULL, 0, &args) == AST_FEATURE_RETURN_PARKFAILED) {
1225                 goto exit_features_test;
1226         }
1227         /* hangup zombie channel */
1228         ast_hangup(test_channel1);
1229         test_channel1 = NULL;
1230         if (!args.pu->parkingnum == 750 || strcasecmp(args.pu->parkinglot->name, unique_parkinglot)) {
1231                 ast_test_status_update(test, "Parking settings were not respected\n");
1232                 goto exit_features_test;
1233         } else {
1234                 ast_test_status_update(test, "Parking settings for masquerading park verified\n");
1235         }
1236         /* find the real channel */
1237         parked_chan = ast_channel_get_by_name("TestChannel1");
1238         if (unpark_test_channel(parked_chan, &args)) {
1239                 goto exit_features_test;
1240         }
1241
1242         res = 0;
1243
1244 exit_features_test:
1245
1246         if (test_channel1) {
1247                 ast_hangup(test_channel1);
1248         }
1249
1250         /* careful, if PARKINGDYNCONTEXT is tested, need to delete context */
1251         ao2_unlink(parkinglots, dynlot);
1252         parkeddynamic = saved_parkeddynamic;
1253         return res ? AST_TEST_FAIL : AST_TEST_PASS;
1254 }
1255 #endif
1256
1257
1258 /*!
1259  * \brief set caller and callee according to the direction
1260  * \param caller, callee, peer, chan, sense
1261  *
1262  * Detect who triggered feature and set callee/caller variables accordingly
1263 */
1264 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
1265         struct ast_channel *peer, struct ast_channel *chan, int sense)
1266 {
1267         if (sense == FEATURE_SENSE_PEER) {
1268                 *caller = peer;
1269                 *callee = chan;
1270         } else {
1271                 *callee = peer;
1272                 *caller = chan;
1273         }
1274 }
1275
1276 /*! 
1277  * \brief support routing for one touch call parking
1278  * \param chan channel parking call
1279  * \param peer channel to be parked
1280  * \param config unsed
1281  * \param code unused
1282  * \param sense feature options
1283  *
1284  * \param data
1285  * Setup channel, set return exten,priority to 's,1'
1286  * answer chan, sleep chan, park call
1287 */
1288 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1289 {
1290         struct ast_channel *parker;
1291         struct ast_channel *parkee;
1292         int res = 0;
1293
1294         set_peers(&parker, &parkee, peer, chan, sense);
1295         /* we used to set chan's exten and priority to "s" and 1
1296            here, but this generates (in some cases) an invalid
1297            extension, and if "s" exists, could errantly
1298            cause execution of extensions you don't expect. It
1299            makes more sense to let nature take its course
1300            when chan finishes, and let the pbx do its thing
1301            and hang up when the park is over.
1302         */
1303         if (chan->_state != AST_STATE_UP)
1304                 res = ast_answer(chan);
1305         if (!res)
1306                 res = ast_safe_sleep(chan, 1000);
1307
1308         if (!res) { /* one direction used to call park_call.... */
1309                 res = masq_park_call_announce(parkee, parker, 0, NULL);
1310                 /* PBX should hangup zombie channel if a masquerade actually occurred (res=0) */
1311         }
1312
1313         return res;
1314 }
1315
1316 /*! \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
1317         other channel during the message, so please don't use this for very long messages
1318  */
1319 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
1320 {
1321         /* First play for caller, put other channel on auto service */
1322         if (ast_autoservice_start(callee_chan))
1323                 return -1;
1324         if (ast_stream_and_wait(caller_chan, audiofile, "")) {
1325                 ast_log(LOG_WARNING, "Failed to play automon message!\n");
1326                 ast_autoservice_stop(callee_chan);
1327                 return -1;
1328         }
1329         if (ast_autoservice_stop(callee_chan))
1330                 return -1;
1331         /* Then play for callee, put other channel on auto service */
1332         if (ast_autoservice_start(caller_chan))
1333                 return -1;
1334         if (ast_stream_and_wait(callee_chan, audiofile, "")) {
1335                 ast_log(LOG_WARNING, "Failed to play automon message !\n");
1336                 ast_autoservice_stop(caller_chan);
1337                 return -1;
1338         }
1339         if (ast_autoservice_stop(caller_chan))
1340                 return -1;
1341         return(0);
1342 }
1343
1344 /*!
1345  * \brief Monitor a channel by DTMF
1346  * \param chan channel requesting monitor
1347  * \param peer channel to be monitored
1348  * \param config
1349  * \param code
1350  * \param sense feature options
1351  *
1352  * \param data
1353  * Check monitor app enabled, setup channels, both caller/callee chans not null
1354  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
1355  * \retval AST_FEATURE_RETURN_SUCCESS on success.
1356  * \retval -1 on error.
1357 */
1358 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1359 {
1360         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1361         int x = 0;
1362         size_t len;
1363         struct ast_channel *caller_chan, *callee_chan;
1364         const char *automon_message_start = NULL;
1365         const char *automon_message_stop = NULL;
1366
1367         if (!monitor_ok) {
1368                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1369                 return -1;
1370         }
1371
1372         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
1373                 monitor_ok = 0;
1374                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1375                 return -1;
1376         }
1377
1378         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1379         if (caller_chan) {      /* Find extra messages */
1380                 automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1381                 automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1382         }
1383
1384         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1385                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1386                         return -1;
1387                 }
1388         }
1389         
1390         if (callee_chan->monitor) {
1391                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1392                 if (!ast_strlen_zero(automon_message_stop)) {
1393                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1394                 }
1395                 callee_chan->monitor->stop(callee_chan, 1);
1396                 return AST_FEATURE_RETURN_SUCCESS;
1397         }
1398
1399         if (caller_chan && callee_chan) {
1400                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1401                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1402                 const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1403
1404                 if (!touch_format)
1405                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1406
1407                 if (!touch_monitor)
1408                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1409         
1410                 if (!touch_monitor_prefix)
1411                         touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
1412         
1413                 if (touch_monitor) {
1414                         len = strlen(touch_monitor) + 50;
1415                         args = alloca(len);
1416                         touch_filename = alloca(len);
1417                         snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
1418                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1419                 } else {
1420                         caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
1421                         callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
1422                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1423                         args = alloca(len);
1424                         touch_filename = alloca(len);
1425                         snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
1426                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1427                 }
1428
1429                 for(x = 0; x < strlen(args); x++) {
1430                         if (args[x] == '/')
1431                                 args[x] = '-';
1432                 }
1433                 
1434                 ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
1435
1436                 pbx_exec(callee_chan, monitor_app, args);
1437                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1438                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1439
1440                 if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
1441                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
1442                 }
1443         
1444                 return AST_FEATURE_RETURN_SUCCESS;
1445         }
1446         
1447         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");   
1448         return -1;
1449 }
1450
1451 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1452 {
1453         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1454         int x = 0;
1455         size_t len;
1456         struct ast_channel *caller_chan, *callee_chan;
1457         const char *mixmonitor_spy_type = "MixMonitor";
1458         int count = 0;
1459
1460         if (!mixmonitor_ok) {
1461                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1462                 return -1;
1463         }
1464
1465         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
1466                 mixmonitor_ok = 0;
1467                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1468                 return -1;
1469         }
1470
1471         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1472
1473         if (!ast_strlen_zero(courtesytone)) {
1474                 if (ast_autoservice_start(callee_chan))
1475                         return -1;
1476                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
1477                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
1478                         ast_autoservice_stop(callee_chan);
1479                         return -1;
1480                 }
1481                 if (ast_autoservice_stop(callee_chan))
1482                         return -1;
1483         }
1484
1485         ast_channel_lock(callee_chan);
1486         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1487         ast_channel_unlock(callee_chan);
1488
1489         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
1490         if (count > 0) {
1491                 
1492                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
1493
1494                 /* Make sure they are running */
1495                 ast_channel_lock(callee_chan);
1496                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1497                 ast_channel_unlock(callee_chan);
1498                 if (count > 0) {
1499                         if (!stopmixmonitor_ok) {
1500                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1501                                 return -1;
1502                         }
1503                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
1504                                 stopmixmonitor_ok = 0;
1505                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1506                                 return -1;
1507                         } else {
1508                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
1509                                 return AST_FEATURE_RETURN_SUCCESS;
1510                         }
1511                 }
1512                 
1513                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");      
1514         }                       
1515
1516         if (caller_chan && callee_chan) {
1517                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
1518                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
1519
1520                 if (!touch_format)
1521                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
1522
1523                 if (!touch_monitor)
1524                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
1525
1526                 if (touch_monitor) {
1527                         len = strlen(touch_monitor) + 50;
1528                         args = alloca(len);
1529                         touch_filename = alloca(len);
1530                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
1531                         snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
1532                 } else {
1533                         caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
1534                         callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
1535                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1536                         args = alloca(len);
1537                         touch_filename = alloca(len);
1538                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
1539                         snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
1540                 }
1541
1542                 for( x = 0; x < strlen(args); x++) {
1543                         if (args[x] == '/')
1544                                 args[x] = '-';
1545                 }
1546
1547                 ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
1548
1549                 pbx_exec(callee_chan, mixmonitor_app, args);
1550                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1551                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1552                 return AST_FEATURE_RETURN_SUCCESS;
1553         
1554         }
1555
1556         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
1557         return -1;
1558
1559 }
1560
1561 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1562 {
1563         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
1564         return AST_FEATURE_RETURN_HANGUP;
1565 }
1566
1567 static int finishup(struct ast_channel *chan)
1568 {
1569         ast_indicate(chan, AST_CONTROL_UNHOLD);
1570
1571         return ast_autoservice_stop(chan);
1572 }
1573
1574 /*!
1575  * \brief Find the context for the transfer
1576  * \param transferer
1577  * \param transferee
1578  * 
1579  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
1580  * \return a context string
1581 */
1582 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
1583 {
1584         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1585         if (ast_strlen_zero(s)) {
1586                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
1587         }
1588         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
1589                 s = transferer->macrocontext;
1590         }
1591         if (ast_strlen_zero(s)) {
1592                 s = transferer->context;
1593         }
1594         return s;  
1595 }
1596
1597 /*!
1598  * \brief Blind transfer user to another extension
1599  * \param chan channel to be transfered
1600  * \param peer channel initiated blind transfer
1601  * \param config
1602  * \param code
1603  * \param data
1604  * \param sense  feature options
1605  * 
1606  * Place chan on hold, check if transferred to parkinglot extension,
1607  * otherwise check extension exists and transfer caller.
1608  * \retval AST_FEATURE_RETURN_SUCCESS.
1609  * \retval -1 on failure.
1610 */
1611 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1612 {
1613         struct ast_channel *transferer;
1614         struct ast_channel *transferee;
1615         const char *transferer_real_context;
1616         char xferto[256];
1617         int res, parkstatus = 0;
1618
1619         set_peers(&transferer, &transferee, peer, chan, sense);
1620         transferer_real_context = real_ctx(transferer, transferee);
1621         /* Start autoservice on chan while we talk to the originator */
1622         ast_autoservice_start(transferee);
1623         ast_indicate(transferee, AST_CONTROL_HOLD);
1624
1625         memset(xferto, 0, sizeof(xferto));
1626
1627         /* Transfer */
1628         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1629         if (res < 0) {
1630                 finishup(transferee);
1631                 return -1; /* error ? */
1632         }
1633         if (res > 0)    /* If they've typed a digit already, handle it */
1634                 xferto[0] = (char) res;
1635
1636         ast_stopstream(transferer);
1637         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1638         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
1639                 finishup(transferee);
1640                 return res;
1641         }
1642         if (!strcmp(xferto, ast_parking_ext())) {
1643                 res = finishup(transferee);
1644                 if (res)
1645                         res = -1;
1646                 else if (!(parkstatus = masq_park_call_announce(transferee, transferer, 0, NULL))) {    /* success */
1647                         /* We return non-zero, but tell the PBX not to hang the channel when
1648                            the thread dies -- We have to be careful now though.  We are responsible for 
1649                            hanging up the channel, else it will never be hung up! */
1650
1651                         return 0;
1652                 } else {
1653                         ast_log(LOG_WARNING, "Unable to park call %s, parkstatus = %d\n", transferee->name, parkstatus);
1654                 }
1655                 /*! \todo XXX Maybe we should have another message here instead of invalid extension XXX */
1656         } else if (ast_exists_extension(transferee, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
1657                 ast_cel_report_event(transferer, AST_CEL_BLINDTRANSFER, NULL, xferto, transferee);
1658                 pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
1659                 pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
1660                 res=finishup(transferee);
1661                 if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
1662                         transferer->cdr=ast_cdr_alloc();
1663                         if (transferer->cdr) {
1664                                 ast_cdr_init(transferer->cdr, transferer); /* initialize our channel's cdr */
1665                                 ast_cdr_start(transferer->cdr);
1666                         }
1667                 }
1668                 if (transferer->cdr) {
1669                         struct ast_cdr *swap = transferer->cdr;
1670                         ast_log(LOG_DEBUG,"transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
1671                                         transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
1672                                         transferer->cdr->channel, transferer->cdr->dstchannel);
1673                         ast_log(LOG_DEBUG,"TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
1674                                         transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
1675                         ast_log(LOG_DEBUG,"transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
1676                         /* swap cdrs-- it will save us some time & work */
1677                         transferer->cdr = transferee->cdr;
1678                         transferee->cdr = swap;
1679                 }
1680                 if (!transferee->pbx) {
1681                         /* Doh!  Use our handy async_goto functions */
1682                         ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
1683                                                                 ,transferee->name, xferto, transferer_real_context);
1684                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
1685                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
1686                 } else {
1687                         /* Set the channel's new extension, since it exists, using transferer context */
1688                         ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
1689                         ast_log(LOG_DEBUG,"ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
1690                         if (ast_channel_connected_line_macro(transferee, transferer, &transferer->connected, 1, 0)) {
1691                                 ast_channel_update_connected_line(transferee, &transferer->connected);
1692                         }
1693                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
1694                 }
1695                 check_goto_on_transfer(transferer);
1696                 return res;
1697         } else {
1698                 ast_verb(3, "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
1699         }
1700         if (parkstatus != AST_FEATURE_RETURN_PARKFAILED && ast_stream_and_wait(transferer, xferfailsound, AST_DIGIT_ANY) < 0) {
1701                 finishup(transferee);
1702                 return -1;
1703         }
1704         ast_stopstream(transferer);
1705         res = finishup(transferee);
1706         if (res) {
1707                 ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
1708                 return res;
1709         }
1710         return AST_FEATURE_RETURN_SUCCESS;
1711 }
1712
1713 /*!
1714  * \brief make channels compatible
1715  * \param c
1716  * \param newchan
1717  * \retval 0 on success.
1718  * \retval -1 on failure.
1719 */
1720 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
1721 {
1722         if (ast_channel_make_compatible(c, newchan) < 0) {
1723                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
1724                         c->name, newchan->name);
1725                 ast_hangup(newchan);
1726                 return -1;
1727         }
1728         return 0;
1729 }
1730
1731 /*!
1732  * \brief Attended transfer
1733  * \param chan transfered user
1734  * \param peer person transfering call
1735  * \param config
1736  * \param code
1737  * \param sense feature options
1738  * 
1739  * \param data
1740  * Get extension to transfer to, if you cannot generate channel (or find extension) 
1741  * return to host channel. After called channel answered wait for hangup of transferer,
1742  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
1743  *
1744  * \return -1 on failure
1745 */
1746 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
1747 {
1748         struct ast_channel *transferer;
1749         struct ast_channel *transferee;
1750         const char *transferer_real_context;
1751         char xferto[256] = "";
1752         int res;
1753         int outstate=0;
1754         struct ast_channel *newchan;
1755         struct ast_channel *xferchan;
1756         struct ast_bridge_thread_obj *tobj;
1757         struct ast_bridge_config bconfig;
1758         struct ast_frame *f;
1759         int l;
1760         struct ast_party_connected_line connected_line;
1761         struct ast_datastore *features_datastore;
1762         struct ast_dial_features *dialfeatures = NULL;
1763
1764         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
1765         set_peers(&transferer, &transferee, peer, chan, sense);
1766         transferer_real_context = real_ctx(transferer, transferee);
1767         /* Start autoservice on chan while we talk to the originator */
1768         ast_autoservice_start(transferee);
1769         ast_indicate(transferee, AST_CONTROL_HOLD);
1770         
1771         /* Transfer */
1772         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1773         if (res < 0) {
1774                 finishup(transferee);
1775                 return res;
1776         }
1777         if (res > 0) /* If they've typed a digit already, handle it */
1778                 xferto[0] = (char) res;
1779
1780         /* this is specific of atxfer */
1781         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1782         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
1783                 finishup(transferee);
1784                 return res;
1785         }
1786         if (res == 0) {
1787                 ast_log(LOG_WARNING, "Did not read data.\n");
1788                 finishup(transferee);
1789                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1790                         return -1;
1791                 return AST_FEATURE_RETURN_SUCCESS;
1792         }
1793
1794         /* valid extension, res == 1 */
1795         if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
1796                 ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
1797                 finishup(transferee);
1798                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1799                         return -1;
1800                 return AST_FEATURE_RETURN_SUCCESS;
1801         }
1802
1803         /* If we are attended transfering to parking, just use builtin_parkcall instead of trying to track all of
1804          * the different variables for handling this properly with a builtin_atxfer */
1805         if (!strcmp(xferto, ast_parking_ext())) {
1806                 finishup(transferee);
1807                 return builtin_parkcall(chan, peer, config, code, sense, data);
1808         }
1809
1810         l = strlen(xferto);
1811         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);     /* append context */
1812
1813         /* If we are performing an attended transfer and we have two channels involved then
1814            copy sound file information to play upon attended transfer completion */
1815         if (transferee) {
1816                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1817                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1818
1819                 if (!ast_strlen_zero(chan1_attended_sound)) {
1820                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
1821                 }
1822                 if (!ast_strlen_zero(chan2_attended_sound)) {
1823                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
1824                 }
1825         }
1826
1827         newchan = feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
1828                 xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
1829
1830         ast_party_connected_line_init(&connected_line);
1831         if (!ast_check_hangup(transferer)) {
1832                 /* Transferer is up - old behaviour */
1833                 ast_indicate(transferer, -1);
1834                 if (!newchan) {
1835                         finishup(transferee);
1836                         /* any reason besides user requested cancel and busy triggers the failed sound */
1837                         if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
1838                                 ast_stream_and_wait(transferer, xferfailsound, ""))
1839                                 return -1;
1840                         if (ast_stream_and_wait(transferer, xfersound, ""))
1841                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1842                         return AST_FEATURE_RETURN_SUCCESS;
1843                 }
1844
1845                 if (check_compat(transferer, newchan)) {
1846                         /* we do mean transferee here, NOT transferer */
1847                         finishup(transferee);
1848                         return -1;
1849                 }
1850                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
1851                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1852                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1853                 /* We need to get the transferer's connected line information copied
1854                  * at this point because he is likely to hang up during the bridge with
1855                  * newchan. This info will be used down below before bridging the 
1856                  * transferee and newchan
1857                  *
1858                  * As a result, we need to be sure to free this data before returning
1859                  * or overwriting it.
1860                  */
1861                 ast_channel_lock(transferer);
1862                 ast_party_connected_line_copy(&connected_line, &transferer->connected);
1863                 ast_channel_unlock(transferer);
1864                 res = ast_bridge_call(transferer, newchan, &bconfig);
1865                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
1866                         ast_hangup(newchan);
1867                         if (ast_stream_and_wait(transferer, xfersound, ""))
1868                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1869                         finishup(transferee);
1870                         transferer->_softhangup = 0;
1871                         ast_party_connected_line_free(&connected_line);
1872                         return AST_FEATURE_RETURN_SUCCESS;
1873                 }
1874
1875                 ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
1876
1877                 if (check_compat(transferee, newchan)) {
1878                         finishup(transferee);
1879                         ast_party_connected_line_free(&connected_line);
1880                         return -1;
1881                 }
1882                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
1883
1884                 if ((ast_autoservice_stop(transferee) < 0)
1885                  || (ast_waitfordigit(transferee, 100) < 0)
1886                  || (ast_waitfordigit(newchan, 100) < 0)
1887                  || ast_check_hangup(transferee)
1888                  || ast_check_hangup(newchan)) {
1889                         ast_hangup(newchan);
1890                         ast_party_connected_line_free(&connected_line);
1891                         return -1;
1892                 }
1893                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
1894                 if (!xferchan) {
1895                         ast_hangup(newchan);
1896                         ast_party_connected_line_free(&connected_line);
1897                         return -1;
1898                 }
1899                 /* Make formats okay */
1900                 xferchan->visible_indication = transferer->visible_indication;
1901                 xferchan->readformat = transferee->readformat;
1902                 xferchan->writeformat = transferee->writeformat;
1903                 ast_channel_masquerade(xferchan, transferee);
1904                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
1905                 xferchan->_state = AST_STATE_UP;
1906                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
1907                 xferchan->_softhangup = 0;
1908                 if ((f = ast_read(xferchan)))
1909                         ast_frfree(f);
1910                 newchan->_state = AST_STATE_UP;
1911                 ast_clear_flag(newchan, AST_FLAGS_ALL);
1912                 newchan->_softhangup = 0;
1913                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
1914                         ast_hangup(xferchan);
1915                         ast_hangup(newchan);
1916                         ast_party_connected_line_free(&connected_line);
1917                         return -1;
1918                 }
1919
1920                 ast_channel_lock(newchan);
1921                 if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
1922                                 dialfeatures = features_datastore->data;
1923                 }
1924                 ast_channel_unlock(newchan);
1925
1926                 if (dialfeatures) {
1927                         /* newchan should always be the callee and shows up as callee in dialfeatures, but for some reason
1928                            I don't currently understand, the abilities of newchan seem to be stored on the caller side */
1929                         ast_copy_flags(&(config->features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
1930                         dialfeatures = NULL;
1931                 }
1932
1933                 ast_channel_lock(xferchan);
1934                 if ((features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL))) {
1935                         dialfeatures = features_datastore->data;
1936                 }
1937                 ast_channel_unlock(xferchan);
1938          
1939                 if (dialfeatures) {
1940                         ast_copy_flags(&(config->features_caller), &(dialfeatures->features_caller), AST_FLAGS_ALL);
1941                 }
1942          
1943                 tobj->chan = newchan;
1944                 tobj->peer = xferchan;
1945                 tobj->bconfig = *config;
1946
1947                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
1948                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
1949                 }
1950
1951                 /* Due to a limitation regarding when callerID is set on a Local channel,
1952                  * we use the transferer's connected line information here.
1953                  */
1954
1955                 /* xferchan is transferee, and newchan is the transfer target
1956                  * So...in a transfer, who is the caller and who is the callee?
1957                  *
1958                  * When the call is originally made, it is clear who is caller and callee.
1959                  * When a transfer occurs, it is my humble opinion that the transferee becomes
1960                  * the caller, and the transfer target is the callee.
1961                  *
1962                  * The problem is that these macros were set with the intention of the original
1963                  * caller and callee taking those roles. A transfer can totally mess things up,
1964                  * to be technical. What sucks even more is that you can't effectively change
1965                  * the macros in the dialplan during the call from the transferer to the transfer
1966                  * target because the transferee is stuck with whatever role he originally had.
1967                  *
1968                  * I think the answer here is just to make sure that it is well documented that
1969                  * during a transfer, the transferee is the "caller" and the transfer target
1970                  * is the "callee."
1971                  *
1972                  * This means that if party A calls party B, and party A transfers party B to
1973                  * party C, then B has switched roles for the call. Now party B will have the
1974                  * caller macro called on his channel instead of the callee macro.
1975                  *
1976                  * Luckily, the method by which the bridge is launched here ensures that the 
1977                  * transferee is the "chan" on the bridge and the transfer target is the "peer,"
1978                  * so my idea for the roles post-transfer does not require extensive code changes.
1979                  */
1980                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1981                 if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
1982                         ast_channel_update_connected_line(xferchan, &connected_line);
1983                 }
1984                 ast_channel_lock(xferchan);
1985                 ast_connected_line_copy_from_caller(&connected_line, &xferchan->cid);
1986                 ast_channel_unlock(xferchan);
1987                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1988                 if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
1989                         ast_channel_update_connected_line(newchan, &connected_line);
1990                 }
1991                 ast_party_connected_line_free(&connected_line);
1992
1993                 if (ast_stream_and_wait(newchan, xfersound, ""))
1994                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1995                 bridge_call_thread_launch(tobj);
1996                 return -1;      /* XXX meaning the channel is bridged ? */
1997         } else if (!ast_check_hangup(transferee)) {
1998                 /* act as blind transfer */
1999                 if (ast_autoservice_stop(transferee) < 0) {
2000                         ast_hangup(newchan);
2001                         return -1;
2002                 }
2003
2004                 if (!newchan) {
2005                         unsigned int tries = 0;
2006                         char *transferer_tech, *transferer_name = ast_strdupa(transferer->name);
2007
2008                         transferer_tech = strsep(&transferer_name, "/");
2009                         transferer_name = strsep(&transferer_name, "-");
2010
2011                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
2012                                 ast_log(LOG_WARNING, "Transferer has invalid channel name: '%s'\n", transferer->name);
2013                                 if (ast_stream_and_wait(transferee, "beeperr", ""))
2014                                         return -1;
2015                                 return AST_FEATURE_RETURN_SUCCESS;
2016                         }
2017
2018                         ast_log(LOG_NOTICE, "We're trying to call %s/%s\n", transferer_tech, transferer_name);
2019                         newchan = feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
2020                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
2021                         while (!newchan && !atxferdropcall && tries < atxfercallbackretries) {
2022                                 /* Trying to transfer again */
2023                                 ast_autoservice_start(transferee);
2024                                 ast_indicate(transferee, AST_CONTROL_HOLD);
2025
2026                                 newchan = feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
2027                                         xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
2028                                 if (ast_autoservice_stop(transferee) < 0) {
2029                                         if (newchan)
2030                                                 ast_hangup(newchan);
2031                                         return -1;
2032                                 }
2033                                 if (!newchan) {
2034                                         /* Transfer failed, sleeping */
2035                                         ast_debug(1, "Sleeping for %d ms before callback.\n", atxferloopdelay);
2036                                         ast_safe_sleep(transferee, atxferloopdelay);
2037                                         ast_debug(1, "Trying to callback...\n");
2038                                         newchan = feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
2039                                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
2040                                 }
2041                                 tries++;
2042                         }
2043                 }
2044                 if (!newchan)
2045                         return -1;
2046
2047                 ast_cel_report_event(transferee, AST_CEL_ATTENDEDTRANSFER, NULL, NULL, newchan);
2048
2049                 /* newchan is up, we should prepare transferee and bridge them */
2050                 if (check_compat(transferee, newchan)) {
2051                         finishup(transferee);
2052                         return -1;
2053                 }
2054                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
2055
2056                 if ((ast_waitfordigit(transferee, 100) < 0)
2057                    || (ast_waitfordigit(newchan, 100) < 0)
2058                    || ast_check_hangup(transferee)
2059                    || ast_check_hangup(newchan)) {
2060                         ast_hangup(newchan);
2061                         return -1;
2062                 }
2063
2064                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", transferee->linkedid, 0, "Transfered/%s", transferee->name);
2065                 if (!xferchan) {
2066                         ast_hangup(newchan);
2067                         return -1;
2068                 }
2069                 /* Make formats okay */
2070                 xferchan->visible_indication = transferer->visible_indication;
2071                 xferchan->readformat = transferee->readformat;
2072                 xferchan->writeformat = transferee->writeformat;
2073                 ast_channel_masquerade(xferchan, transferee);
2074                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
2075                 xferchan->_state = AST_STATE_UP;
2076                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
2077                 xferchan->_softhangup = 0;
2078                 if ((f = ast_read(xferchan)))
2079                         ast_frfree(f);
2080                 newchan->_state = AST_STATE_UP;
2081                 ast_clear_flag(newchan, AST_FLAGS_ALL);
2082                 newchan->_softhangup = 0;
2083                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
2084                         ast_hangup(xferchan);
2085                         ast_hangup(newchan);
2086                         return -1;
2087                 }
2088                 tobj->chan = newchan;
2089                 tobj->peer = xferchan;
2090                 tobj->bconfig = *config;
2091                 
2092                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
2093                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
2094                 }
2095
2096                 ast_channel_lock(newchan);
2097                 ast_connected_line_copy_from_caller(&connected_line, &newchan->cid);
2098                 ast_channel_unlock(newchan);
2099                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2100                 if (ast_channel_connected_line_macro(newchan, xferchan, &connected_line, 1, 0)) {
2101                         ast_channel_update_connected_line(xferchan, &connected_line);
2102                 }
2103                 ast_channel_lock(xferchan);
2104                 ast_connected_line_copy_from_caller(&connected_line, &xferchan->cid);
2105                 ast_channel_unlock(xferchan);
2106                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
2107                 if (ast_channel_connected_line_macro(xferchan, newchan, &connected_line, 0, 0)) {
2108                         ast_channel_update_connected_line(newchan, &connected_line);
2109                 }
2110
2111                 ast_party_connected_line_free(&connected_line);
2112                 
2113                 if (ast_stream_and_wait(newchan, xfersound, ""))
2114                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
2115                 bridge_call_thread_launch(tobj);
2116                 return -1;      /* XXX meaning the channel is bridged ? */
2117         } else {
2118                 /* Transferee hung up */
2119                 finishup(transferee);
2120                 return -1;
2121         }
2122 }
2123
2124 /* add atxfer and automon as undefined so you can only use em if you configure them */
2125 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
2126
2127 AST_RWLOCK_DEFINE_STATIC(features_lock);
2128
2129 static struct ast_call_feature builtin_features[] = {
2130         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2131         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2132         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2133         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2134         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2135         { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
2136 };
2137
2138
2139 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
2140
2141 /*! \brief register new feature into feature_list*/
2142 void ast_register_feature(struct ast_call_feature *feature)
2143 {
2144         if (!feature) {
2145                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
2146                 return;
2147         }
2148   
2149         AST_RWLIST_WRLOCK(&feature_list);
2150         AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
2151         AST_RWLIST_UNLOCK(&feature_list);
2152
2153         ast_verb(2, "Registered Feature '%s'\n",feature->sname);
2154 }
2155
2156 /*! 
2157  * \brief Add new feature group
2158  * \param fgname feature group name.
2159  *
2160  * Add new feature group to the feature group list insert at head of list.
2161  * \note This function MUST be called while feature_groups is locked.
2162 */
2163 static struct feature_group* register_group(const char *fgname)
2164 {
2165         struct feature_group *fg;
2166
2167         if (!fgname) {
2168                 ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
2169                 return NULL;
2170         }
2171
2172         if (!(fg = ast_calloc_with_stringfields(1, struct feature_group, 128)))
2173                 return NULL;
2174
2175         ast_string_field_set(fg, gname, fgname);
2176
2177         AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
2178
2179         ast_verb(2, "Registered group '%s'\n", fg->gname);
2180
2181         return fg;
2182 }
2183
2184 /*! 
2185  * \brief Add feature to group
2186  * \param fg feature group
2187  * \param exten
2188  * \param feature feature to add.
2189  *
2190  * Check fg and feature specified, add feature to list
2191  * \note This function MUST be called while feature_groups is locked. 
2192 */
2193 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature) 
2194 {
2195         struct feature_group_exten *fge;
2196
2197         if (!fg) {
2198                 ast_log(LOG_NOTICE, "You didn't pass a group!\n");
2199                 return;
2200         }
2201
2202         if (!feature) {
2203                 ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
2204                 return;
2205         }
2206
2207         if (!(fge = ast_calloc_with_stringfields(1, struct feature_group_exten, 128)))
2208                 return;
2209
2210         ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
2211
2212         fge->feature = feature;
2213
2214         AST_LIST_INSERT_HEAD(&fg->features, fge, entry);                
2215
2216         ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
2217                                         feature->sname, fg->gname, exten);
2218 }
2219
2220 void ast_unregister_feature(struct ast_call_feature *feature)
2221 {
2222         if (!feature) {
2223                 return;
2224         }
2225
2226         AST_RWLIST_WRLOCK(&feature_list);
2227         AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
2228         AST_RWLIST_UNLOCK(&feature_list);
2229
2230         ast_free(feature);
2231 }
2232
2233 /*! \brief Remove all features in the list */
2234 static void ast_unregister_features(void)
2235 {
2236         struct ast_call_feature *feature;
2237
2238         AST_RWLIST_WRLOCK(&feature_list);
2239         while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
2240                 ast_free(feature);
2241         }
2242         AST_RWLIST_UNLOCK(&feature_list);
2243 }
2244
2245 /*! \brief find a call feature by name */
2246 static struct ast_call_feature *find_dynamic_feature(const char *name)
2247 {
2248         struct ast_call_feature *tmp;
2249
2250         AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
2251                 if (!strcasecmp(tmp->sname, name)) {
2252                         break;
2253                 }
2254         }
2255
2256         return tmp;
2257 }
2258
2259 /*! \brief Remove all feature groups in the list */
2260 static void ast_unregister_groups(void)
2261 {
2262         struct feature_group *fg;
2263         struct feature_group_exten *fge;
2264
2265         AST_RWLIST_WRLOCK(&feature_groups);
2266         while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
2267                 while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
2268                         ast_string_field_free_memory(fge);
2269                         ast_free(fge);
2270                 }
2271
2272                 ast_string_field_free_memory(fg);
2273                 ast_free(fg);
2274         }
2275         AST_RWLIST_UNLOCK(&feature_groups);
2276 }
2277
2278 /*! 
2279  * \brief Find a group by name 
2280  * \param name feature name
2281  * \retval feature group on success.
2282  * \retval NULL on failure.
2283 */
2284 static struct feature_group *find_group(const char *name) {
2285         struct feature_group *fg = NULL;
2286
2287         AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
2288                 if (!strcasecmp(fg->gname, name))
2289                         break;
2290         }
2291
2292         return fg;
2293 }
2294
2295 void ast_rdlock_call_features(void)
2296 {
2297         ast_rwlock_rdlock(&features_lock);
2298 }
2299
2300 void ast_unlock_call_features(void)
2301 {
2302         ast_rwlock_unlock(&features_lock);
2303 }
2304
2305 struct ast_call_feature *ast_find_call_feature(const char *name)
2306 {
2307         int x;
2308         for (x = 0; x < FEATURES_COUNT; x++) {
2309                 if (!strcasecmp(name, builtin_features[x].sname))
2310                         return &builtin_features[x];
2311         }
2312         return NULL;
2313 }
2314
2315 /*!
2316  * \brief exec an app by feature 
2317  * \param chan,peer,config,code,sense,data
2318  *
2319  * Find a feature, determine which channel activated
2320  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
2321  * \retval -1 error.
2322  * \retval -2 when an application cannot be found.
2323 */
2324 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense, void *data)
2325 {
2326         struct ast_app *app;
2327         struct ast_call_feature *feature = data;
2328         struct ast_channel *work, *idle;
2329         int res;
2330
2331         if (!feature) { /* shouldn't ever happen! */
2332                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
2333                 return -1; 
2334         }
2335
2336         if (sense == FEATURE_SENSE_CHAN) {
2337                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2338                         return AST_FEATURE_RETURN_KEEPTRYING;
2339                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2340                         work = chan;
2341                         idle = peer;
2342                 } else {
2343                         work = peer;
2344                         idle = chan;
2345                 }
2346         } else {
2347                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2348                         return AST_FEATURE_RETURN_KEEPTRYING;
2349                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
2350                         work = peer;
2351                         idle = chan;
2352                 } else {
2353                         work = chan;
2354                         idle = peer;
2355                 }
2356         }
2357
2358         if (!(app = pbx_findapp(feature->app))) {
2359                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
2360                 return -2;
2361         }
2362
2363         ast_autoservice_start(idle);
2364         
2365         if(work && idle) {
2366                 pbx_builtin_setvar_helper(work, "DYNAMIC_PEERNAME", idle->name);
2367                 pbx_builtin_setvar_helper(idle, "DYNAMIC_PEERNAME", work->name);
2368                 pbx_builtin_setvar_helper(work, "DYNAMIC_FEATURENAME", feature->sname);
2369                 pbx_builtin_setvar_helper(idle, "DYNAMIC_FEATURENAME", feature->sname);
2370         }
2371
2372         if (!ast_strlen_zero(feature->moh_class))
2373                 ast_moh_start(idle, feature->moh_class, NULL);
2374
2375         res = pbx_exec(work, app, feature->app_args);
2376
2377         if (!ast_strlen_zero(feature->moh_class))
2378                 ast_moh_stop(idle);
2379
2380         ast_autoservice_stop(idle);
2381
2382         if (res) {
2383                 return AST_FEATURE_RETURN_SUCCESSBREAK;
2384         }
2385         return AST_FEATURE_RETURN_SUCCESS;      /*! \todo XXX should probably return res */
2386 }
2387
2388 static void unmap_features(void)
2389 {
2390         int x;
2391
2392         ast_rwlock_wrlock(&features_lock);
2393         for (x = 0; x < FEATURES_COUNT; x++)
2394                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
2395         ast_rwlock_unlock(&features_lock);
2396 }
2397
2398 static int remap_feature(const char *name, const char *value)
2399 {
2400         int x, res = -1;
2401
2402         ast_rwlock_wrlock(&features_lock);
2403         for (x = 0; x < FEATURES_COUNT; x++) {
2404                 if (strcasecmp(builtin_features[x].sname, name))
2405                         continue;
2406
2407                 ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
2408                 res = 0;
2409                 break;
2410         }
2411         ast_rwlock_unlock(&features_lock);
2412
2413         return res;
2414 }
2415
2416 /*!
2417  * \brief Helper function for feature_interpret and ast_feature_detect
2418  * \param chan,peer,config,code,sense,dynamic_features char buf,feature flags,operation,feature
2419  *
2420  * Lock features list, browse for code, unlock list
2421  * If a feature is found and the operation variable is set, that feature's
2422  * operation is executed.  The first feature found is copied to the feature parameter.
2423  * \retval res on success.
2424  * \retval -1 on failure.
2425 */
2426 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
2427         struct ast_bridge_config *config, const char *code, int sense, char *dynamic_features_buf,
2428         struct ast_flags *features, int operation, struct ast_call_feature *feature)
2429 {
2430         int x;
2431         struct feature_group *fg = NULL;
2432         struct feature_group_exten *fge;
2433         struct ast_call_feature *tmpfeature;
2434         char *tmp, *tok;
2435         int res = AST_FEATURE_RETURN_PASSDIGITS;
2436         int feature_detected = 0;
2437
2438         if (!(peer && chan && config) && operation) {
2439                 return -1; /* can not run feature operation */
2440         }
2441
2442         ast_rwlock_rdlock(&features_lock);
2443         for (x = 0; x < FEATURES_COUNT; x++) {
2444                 if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
2445                     !ast_strlen_zero(builtin_features[x].exten)) {
2446                         /* Feature is up for consideration */
2447                         if (!strcmp(builtin_features[x].exten, code)) {
2448                                 ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
2449                                 if (operation) {
2450                                         res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
2451                                 }
2452                                 memcpy(feature, &builtin_features[x], sizeof(feature));
2453                                 feature_detected = 1;
2454                                 break;
2455                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
2456                                 if (res == AST_FEATURE_RETURN_PASSDIGITS)
2457                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2458                         }
2459                 }
2460         }
2461         ast_rwlock_unlock(&features_lock);
2462
2463         if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
2464                 return res;
2465         }
2466
2467         tmp = dynamic_features_buf;
2468
2469         while ((tok = strsep(&tmp, "#"))) {
2470                 AST_RWLIST_RDLOCK(&feature_groups);
2471
2472                 fg = find_group(tok);
2473
2474                 if (fg) {
2475                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2476                                 if (strcasecmp(fge->exten, code))
2477                                         continue;
2478                                 if (operation) {
2479                                         res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
2480                                 }
2481                                 memcpy(feature, fge->feature, sizeof(feature));
2482                                 if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2483                                         AST_RWLIST_UNLOCK(&feature_groups);
2484                                         break;
2485                                 }
2486                                 res = AST_FEATURE_RETURN_PASSDIGITS;
2487                         }
2488                         if (fge)
2489                                 break;
2490                 }
2491
2492                 AST_RWLIST_UNLOCK(&feature_groups);
2493
2494                 AST_RWLIST_RDLOCK(&feature_list);
2495
2496                 if (!(tmpfeature = find_dynamic_feature(tok))) {
2497                         AST_RWLIST_UNLOCK(&feature_list);
2498                         continue;
2499                 }
2500
2501                 /* Feature is up for consideration */
2502                 if (!strcmp(tmpfeature->exten, code)) {
2503                         ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
2504                         if (operation) {
2505                                 res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
2506                         }
2507                         memcpy(feature, tmpfeature, sizeof(feature));
2508                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2509                                 AST_RWLIST_UNLOCK(&feature_list);
2510                                 break;
2511                         }
2512                         res = AST_FEATURE_RETURN_PASSDIGITS;
2513                 } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
2514                         res = AST_FEATURE_RETURN_STOREDIGITS;
2515
2516                 AST_RWLIST_UNLOCK(&feature_list);
2517         }
2518
2519         return res;
2520 }
2521
2522 /*!
2523  * \brief Check the dynamic features
2524  * \param chan,peer,config,code,sense
2525  *
2526  * \retval res on success.
2527  * \retval -1 on failure.
2528 */
2529
2530 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, const char *code, int sense) {
2531
2532         char dynamic_features_buf[128];
2533         const char *peer_dynamic_features, *chan_dynamic_features;
2534         struct ast_flags features;
2535         struct ast_call_feature feature;
2536         if (sense == FEATURE_SENSE_CHAN) {
2537                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
2538         }
2539         else {
2540                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
2541         }
2542
2543         ast_channel_lock(peer);
2544         peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
2545         ast_channel_unlock(peer);
2546
2547         ast_channel_lock(chan);
2548         chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
2549         ast_channel_unlock(chan);
2550
2551         snprintf(dynamic_features_buf, sizeof(dynamic_features_buf), "%s%s%s", S_OR(chan_dynamic_features, ""), chan_dynamic_features && peer_dynamic_features ? "#" : "", S_OR(peer_dynamic_features,""));
2552
2553         ast_debug(3, "Feature interpret: chan=%s, peer=%s, code=%s, sense=%d, features=%d, dynamic=%s\n", chan->name, peer->name, code, sense, features.flags, dynamic_features_buf);
2554
2555         return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, 1, &feature);
2556 }
2557
2558
2559 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, const char *code, struct ast_call_feature *feature) {
2560
2561         return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, 0, feature);
2562 }
2563
2564 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2565 {
2566         int x;
2567
2568         ast_clear_flag(config, AST_FLAGS_ALL);
2569
2570         ast_rwlock_rdlock(&features_lock);
2571         for (x = 0; x < FEATURES_COUNT; x++) {
2572                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
2573                         continue;
2574
2575                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
2576                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2577
2578                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
2579                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2580         }
2581         ast_rwlock_unlock(&features_lock);
2582
2583         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2584                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
2585
2586                 if (dynamic_features) {
2587                         char *tmp = ast_strdupa(dynamic_features);
2588                         char *tok;
2589                         struct ast_call_feature *feature;
2590
2591                         /* while we have a feature */
2592                         while ((tok = strsep(&tmp, "#"))) {
2593                                 AST_RWLIST_RDLOCK(&feature_list);
2594                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2595                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2596                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2597                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2598                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2599                                 }
2600                                 AST_RWLIST_UNLOCK(&feature_list);
2601                         }
2602                 }
2603         }
2604 }
2605
2606 /*! 
2607  * \brief Get feature and dial
2608  * \param caller,transferee,type,format,data,timeout,outstate,cid_num,cid_name,igncallerstate
2609  *
2610  * Request channel, set channel variables, initiate call,check if they want to disconnect
2611  * go into loop, check if timeout has elapsed, check if person to be transfered hung up,
2612  * check for answer break loop, set cdr return channel.
2613  *
2614  * \todo XXX Check - this is very similar to the code in channel.c 
2615  * \return always a channel
2616 */
2617 static struct ast_channel *feature_request_and_dial(struct ast_channel *caller, struct ast_channel *transferee, const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, int igncallerstate, const char *language)
2618 {
2619         int state = 0;
2620         int cause = 0;
2621         int to;
2622         struct ast_channel *chan;
2623         struct ast_channel *monitor_chans[2];
2624         struct ast_channel *active_channel;
2625         int res = 0, ready = 0;
2626         struct timeval started;
2627         int x, len = 0;
2628         char *disconnect_code = NULL, *dialed_code = NULL;
2629
2630         if (!(chan = ast_request(type, format, caller, data, &cause))) {
2631                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2632                 switch(cause) {
2633                 case AST_CAUSE_BUSY:
2634                         state = AST_CONTROL_BUSY;
2635                         break;
2636                 case AST_CAUSE_CONGESTION:
2637                         state = AST_CONTROL_CONGESTION;
2638                         break;
2639                 }
2640                 goto done;
2641         }
2642
2643         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2644         ast_string_field_set(chan, language, language);
2645         ast_channel_inherit_variables(caller, chan);    
2646         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
2647                 
2648         ast_channel_lock(chan);
2649         ast_connected_line_copy_from_caller(&chan->connected, &caller->cid);
2650         ast_channel_unlock(chan);
2651         
2652         if (ast_call(chan, data, timeout)) {
2653                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2654                 goto done;
2655         }
2656         
2657         ast_indicate(caller, AST_CONTROL_RINGING);
2658         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2659         ast_rwlock_rdlock(&features_lock);
2660         for (x = 0; x < FEATURES_COUNT; x++) {
2661                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
2662                         continue;
2663
2664                 disconnect_code = builtin_features[x].exten;
2665                 len = strlen(disconnect_code) + 1;
2666                 dialed_code = alloca(len);
2667                 memset(dialed_code, 0, len);
2668                 break;
2669         }
2670         ast_rwlock_unlock(&features_lock);
2671         x = 0;
2672         started = ast_tvnow();
2673         to = timeout;
2674
2675         ast_poll_channel_add(caller, chan);
2676
2677         while (!((transferee && ast_check_hangup(transferee)) && (!igncallerstate && ast_check_hangup(caller))) && timeout && (chan->_state != AST_STATE_UP)) {
2678                 struct ast_frame *f = NULL;
2679
2680                 monitor_chans[0] = caller;
2681                 monitor_chans[1] = chan;
2682                 active_channel = ast_waitfor_n(monitor_chans, 2, &to);
2683
2684                 /* see if the timeout has been violated */
2685                 if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2686                         state = AST_CONTROL_UNHOLD;
2687                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
2688                         break; /*doh! timeout*/
2689                 }
2690
2691                 if (!active_channel)
2692                         continue;
2693
2694                 if (chan && (chan == active_channel)){
2695                         if (!ast_strlen_zero(chan->call_forward)) {
2696                                 if (!(chan = ast_call_forward(caller, chan, &to, format, NULL, outstate))) {
2697                                         return NULL;
2698                                 }
2699                                 continue;
2700                         }
2701                         f = ast_read(chan);
2702                         if (f == NULL) { /*doh! where'd he go?*/
2703                                 state = AST_CONTROL_HANGUP;
2704                                 res = 0;
2705                                 break;
2706                         }
2707                         
2708                         if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
2709                                 if (f->subclass.integer == AST_CONTROL_RINGING) {
2710                                         state = f->subclass.integer;
2711                                         ast_verb(3, "%s is ringing\n", chan->name);
2712                                         ast_indicate(caller, AST_CONTROL_RINGING);
2713                                 } else if ((f->subclass.integer == AST_CONTROL_BUSY) || (f->subclass.integer == AST_CONTROL_CONGESTION)) {
2714                                         state = f->subclass.integer;
2715                                         ast_verb(3, "%s is busy\n", chan->name);
2716                                         ast_indicate(caller, AST_CONTROL_BUSY);
2717                                         ast_frfree(f);
2718                                         f = NULL;
2719                                         break;
2720                                 } else if (f->subclass.integer == AST_CONTROL_ANSWER) {
2721                                         /* This is what we are hoping for */
2722                                         state = f->subclass.integer;
2723                                         ast_frfree(f);
2724                                         f = NULL;
2725                                         ready=1;
2726                                         break;
2727                                 } else if (f->subclass.integer == AST_CONTROL_CONNECTED_LINE) {
2728                                         if (ast_channel_connected_line_macro(chan, caller, f, 1, 1)) {
2729                                                 ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
2730                                         }
2731                                 } else if (f->subclass.integer != -1 && f->subclass.integer != AST_CONTROL_PROGRESS) {
2732                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass.integer);
2733                                 }
2734                                 /* else who cares */
2735                         } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
2736                                 ast_write(caller, f);
2737                         }
2738
2739                 } else if (caller && (active_channel == caller)) {
2740                         f = ast_read(caller);
2741                         if (f == NULL) { /*doh! where'd he go?*/
2742                                 if (!igncallerstate) {
2743                                         if (ast_check_hangup(caller) && !ast_check_hangup(chan)) {
2744                                                 /* make this a blind transfer */
2745                                                 ready = 1;
2746                                                 break;
2747                                         }
2748                                         state = AST_CONTROL_HANGUP;
2749                                         res = 0;
2750                                         break;
2751                                 }
2752                         } else {
2753                         
2754                                 if (f->frametype == AST_FRAME_DTMF) {
2755                                         dialed_code[x++] = f->subclass.integer;
2756                                         dialed_code[x] = '\0';
2757                                         if (strlen(dialed_code) == len) {
2758                                                 x = 0;
2759                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
2760                                                 x = 0;
2761                                                 dialed_code[x] = '\0';
2762                                         }
2763                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
2764                                                 /* Caller Canceled the call */
2765                                                 state = AST_CONTROL_UNHOLD;
2766                                                 ast_frfree(f);
2767                                                 f = NULL;
2768                                                 break;
2769                                         }
2770                                 } else if (f->frametype == AST_FRAME_VOICE || f->frametype == AST_FRAME_VIDEO) {
2771                                         ast_write(chan, f);
2772                                 }
2773                         }
2774                 }
2775                 if (f)
2776                         ast_frfree(f);
2777         } /* end while */
2778
2779         ast_poll_channel_del(caller, chan);
2780                 
2781 done:
2782         ast_indicate(caller, -1);
2783         if (chan && ready) {
2784                 if (chan->_state == AST_STATE_UP) 
2785                         state = AST_CONTROL_ANSWER;
2786                 res = 0;
2787         } else if (chan) {
2788                 res = -1;
2789                 ast_hangup(chan);
2790                 chan = NULL;
2791         } else {
2792                 res = -1;
2793         }
2794         
2795         if (outstate)
2796                 *outstate = state;
2797
2798         return chan;
2799 }
2800
2801 void ast_channel_log(char *title, struct ast_channel *chan);
2802
2803 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
2804 {
2805        ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long)chan);
2806        ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
2807                        chan->name, chan->appl, chan->data, chan->context, chan->exten, chan->priority);
2808        ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
2809                        chan->accountcode, chan->dialcontext, chan->amaflags, chan->macrocontext, chan->macroexten, chan->macropriority);
2810        ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; _bridge: %p; uniqueID: %s; linkedID:%s\n",
2811                        chan->masq, chan->masqr,
2812                        chan->_bridge, chan->uniqueid, chan->linkedid);
2813        if (chan->masqr)
2814                ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
2815                                chan->masqr->name, chan->masqr->cdr);
2816        if (chan->_bridge)
2817                ast_log(LOG_NOTICE, "CHAN: Bridged to %s\n", chan->_bridge->name);
2818
2819         ast_log(LOG_NOTICE, "===== done ====\n");
2820 }
2821
2822 /*!
2823  * \brief return the first unlocked cdr in a possible chain
2824 */
2825 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
2826 {
2827         struct ast_cdr *cdr_orig = cdr;
2828         while (cdr) {
2829                 if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
2830                         return cdr;
2831                 cdr = cdr->next;
2832         }
2833         return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
2834 }
2835
2836 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
2837 {
2838         const char *feature;
2839
2840         if (ast_strlen_zero(features)) {
2841                 return;
2842         }
2843
2844         for (feature = features; *feature; feature++) {
2845                 switch (*feature) {
2846                 case 'T' :
2847                 case 't' :
2848                         ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
2849                         break;
2850                 case 'K' :
2851                 case 'k' :
2852                         ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
2853                         break;
2854                 case 'H' :
2855                 case 'h' :
2856                         ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
2857                         break;
2858                 case 'W' :
2859                 case 'w' :
2860                         ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
2861                         break;
2862                 default :
2863                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
2864                 }
2865         }
2866 }
2867
2868 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
2869 {
2870         struct ast_datastore *ds_callee_features = NULL, *ds_caller_features = NULL;
2871         struct ast_dial_features *callee_features = NULL, *caller_features = NULL;
2872
2873         ast_channel_lock(caller);
2874         ds_caller_features = ast_channel_datastore_find(caller, &dial_features_info, NULL);
2875         ast_channel_unlock(caller);
2876         if (!ds_caller_features) {
2877                 if (!(ds_caller_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2878                         ast_log(LOG_WARNING, "Unable to create channel datastore for caller features. Aborting!\n");
2879                         return;
2880                 }
2881                 if (!(caller_features = ast_calloc(1, sizeof(*caller_features)))) {
2882                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2883                         ast_datastore_free(ds_caller_features);
2884                         return;
2885                 }
2886                 ds_caller_features->inheritance = DATASTORE_INHERIT_FOREVER;
2887                 caller_features->is_caller = 1;
2888                 ast_copy_flags(&(caller_features->features_callee), &(config->features_callee), AST_FLAGS_ALL);
2889                 ast_copy_flags(&(caller_features->features_caller), &(config->features_caller), AST_FLAGS_ALL);
2890                 ds_caller_features->data = caller_features;
2891                 ast_channel_lock(caller);
2892                 ast_channel_datastore_add(caller, ds_caller_features);
2893                 ast_channel_unlock(caller);
2894         } else {
2895                 /* If we don't return here, then when we do a builtin_atxfer we will copy the disconnect
2896                  * flags over from the atxfer to the caller */
2897                 return;
2898         }
2899
2900         ast_channel_lock(callee);
2901         ds_callee_features = ast_channel_datastore_find(callee, &dial_features_info, NULL);
2902         ast_channel_unlock(callee);
2903         if (!ds_callee_features) {
2904                 if (!(ds_callee_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2905                         ast_log(LOG_WARNING, "Unable to create channel datastore for callee features. Aborting!\n");
2906                         return;
2907                 }
2908                 if (!(callee_features = ast_calloc(1, sizeof(*callee_features)))) {
2909                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2910                         ast_datastore_free(ds_callee_features);
2911                         return;
2912                 }
2913                 ds_callee_features->inheritance = DATASTORE_INHERIT_FOREVER;
2914                 callee_features->is_caller = 0;
2915                 ast_copy_flags(&(callee_features->features_callee), &(config->features_caller), AST_FLAGS_ALL);
2916                 ast_copy_flags(&(callee_features->features_caller), &(config->features_callee), AST_FLAGS_ALL);
2917                 ds_callee_features->data = callee_features;
2918                 ast_channel_lock(callee);
2919                 ast_channel_datastore_add(callee, ds_callee_features);
2920                 ast_channel_unlock(callee);
2921         }
2922
2923         return;
2924 }
2925
2926 /*!
2927  * \brief bridge the call and set CDR
2928  * \param chan,peer,config
2929  * 
2930  * Set start time, check for two channels,check if monitor on
2931  * check for feature activation, create new CDR
2932  * \retval res on success.
2933  * \retval -1 on failure to bridge.
2934 */
2935 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
2936 {
2937         /* Copy voice back and forth between the two channels.  Give the peer
2938            the ability to transfer calls with '#<extension' syntax. */
2939         struct ast_frame *f;
2940         struct ast_channel *who;
2941         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
2942         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
2943         char orig_channame[AST_MAX_EXTENSION];
2944         char orig_peername[AST_MAX_EXTENSION];
2945         int res;
2946         int diff;
2947         int hasfeatures=0;
2948         int hadfeatures=0;
2949         int autoloopflag;
2950         struct ast_option_header *aoh;
2951         struct ast_cdr *bridge_cdr = NULL;
2952         struct ast_cdr *orig_peer_cdr = NULL;
2953         struct ast_cdr *chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2954         struct ast_cdr *peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2955         struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2956         struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2957
2958         if (chan && peer) {
2959                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
2960                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
2961         } else if (chan) {
2962                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
2963         }
2964
2965         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
2966         add_features_datastores(chan, peer, config);
2967
2968         /* This is an interesting case.  One example is if a ringing channel gets redirected to
2969          * an extension that picks up a parked call.  This will make sure that the call taken
2970          * out of parking gets told that the channel it just got bridged to is still ringing. */
2971         if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
2972                 ast_indicate(peer, AST_CONTROL_RINGING);
2973         }
2974
2975         if (monitor_ok) {
2976                 const char *monitor_exec;
2977                 struct ast_channel *src = NULL;
2978                 if (!monitor_app) {
2979                         if (!(monitor_app = pbx_findapp("Monitor")))
2980                                 monitor_ok=0;
2981                 }
2982                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
2983                         src = chan;
2984                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
2985                         src = peer;
2986                 if (monitor_app && src) {
2987                         char *tmp = ast_strdupa(monitor_exec);
2988                         pbx_exec(src, monitor_app, tmp);
2989                 }
2990         }
2991
2992         set_config_flags(chan, peer, config);
2993
2994         /* Answer if need be */
2995         if (chan->_state != AST_STATE_UP) {
2996                 if (ast_raw_answer(chan, 1)) {
2997                         return -1;
2998                 }
2999         }
3000
3001 #ifdef FOR_DEBUG
3002         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
3003         ast_channel_log("Pre-bridge CHAN Channel info", chan);
3004         ast_channel_log("Pre-bridge PEER Channel info", peer);
3005 #endif
3006         /* two channels are being marked as linked here */
3007         ast_channel_set_linkgroup(chan,peer);
3008
3009         /* copy the userfield from the B-leg to A-leg if applicable */
3010         if (chan->cdr && peer->cdr && !ast_strlen_zero(peer->cdr->userfield)) {
3011                 char tmp[256];
3012                 if (!ast_strlen_zero(chan->cdr->userfield)) {
3013                         snprintf(tmp, sizeof(tmp), "%s;%s", chan->cdr->userfield, peer->cdr->userfield);
3014                         ast_cdr_appenduserfield(chan, tmp);
3015                 } else
3016                         ast_cdr_setuserfield(chan, peer->cdr->userfield);
3017                 /* free the peer's cdr without ast_cdr_free complaining */
3018                 ast_free(peer->cdr);
3019                 peer->cdr = NULL;
3020         }
3021         ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
3022         ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
3023         orig_peer_cdr = peer_cdr;
3024         
3025         if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
3026                 
3027                 if (chan_cdr) {
3028                         ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
3029                         ast_cdr_update(chan);
3030                         bridge_cdr = ast_cdr_dup_unique_swap(chan_cdr);
3031                         ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
3032                         ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
3033                         if (peer_cdr && !ast_strlen_zero(peer_cdr->userfield)) {
3034                                 ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
3035                         }
3036                         ast_cdr_setaccount(peer, chan->accountcode);
3037