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