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