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