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