Fix a typo where an equality check should be an assignment.
[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_channel_get_by_name(other_side))) {
724                                 ast_channel_lock(tmpchan);
725                                 if ((base_peer = ast_bridged_channel(tmpchan))) {
726                                         ast_copy_string(pu->peername, base_peer->name, sizeof(pu->peername));
727                                 }
728                                 ast_channel_unlock(tmpchan);
729                                 tmpchan = ast_channel_unref(tmpchan);
730                         }
731                 } else {
732                         ast_copy_string(pu->peername, S_OR(args->orig_chan_name, peer->name), sizeof(pu->peername));
733                 }
734         }
735
736         /* Remember what had been dialed, so that if the parking
737            expires, we try to come back to the same place */
738         ast_copy_string(pu->context, 
739                 S_OR(args->return_con, S_OR(chan->macrocontext, chan->context)), 
740                 sizeof(pu->context));
741         ast_copy_string(pu->exten, 
742                 S_OR(args->return_ext, S_OR(chan->macroexten, chan->exten)), 
743                 sizeof(pu->exten));
744         pu->priority = pu->priority ? pu->priority : 
745                 (chan->macropriority ? chan->macropriority : chan->priority);
746
747         /* If parking a channel directly, don't quiet yet get parking running on it.
748          * All parking lot entries are put into the parking lot with notquiteyet on. */
749         if (peer != chan) 
750                 pu->notquiteyet = 0;
751
752         /* Wake up the (presumably select()ing) thread */
753         pthread_kill(parking_thread, SIGURG);
754         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));
755
756         if (peer) {
757                 event_from = peer->name;
758         } else {
759                 event_from = pbx_builtin_getvar_helper(chan, "BLINDTRANSFER");
760         }
761
762         manager_event(EVENT_FLAG_CALL, "ParkedCall",
763                 "Exten: %s\r\n"
764                 "Channel: %s\r\n"
765                 "Parkinglot: %s\r\n"
766                 "From: %s\r\n"
767                 "Timeout: %ld\r\n"
768                 "CallerIDNum: %s\r\n"
769                 "CallerIDName: %s\r\n"
770                 "Uniqueid: %s\r\n",
771                 pu->parkingexten, pu->chan->name, pu->parkinglot->name, event_from ? event_from : "",
772                 (long)pu->start.tv_sec + (long)(pu->parkingtime/1000) - (long)time(NULL),
773                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
774                 S_OR(pu->chan->cid.cid_name, "<unknown>"),
775                 pu->chan->uniqueid
776                 );
777
778         if (peer && adsipark && ast_adsi_available(peer)) {
779                 adsi_announce_park(peer, pu->parkingexten);     /* Only supports parking numbers */
780                 ast_adsi_unload_session(peer);
781         }
782
783         con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con, registrar);
784         if (!con)       /* Still no context? Bad */
785                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con);
786         if (con) {
787                 if (!ast_add_extension2(con, 1, pu->parkingexten, 1, NULL, NULL, parkedcall, ast_strdup(pu->parkingexten), ast_free_ptr, registrar))
788                         notify_metermaids(pu->parkingexten, pu->parkinglot->parking_con, AST_DEVICE_INUSE);
789         }
790
791         AST_LIST_UNLOCK(&pu->parkinglot->parkings);
792
793         /* Only say number if it's a number and the channel hasn't been masqueraded away */
794         if (peer && !ast_test_flag(args, AST_PARK_OPT_SILENCE) && (ast_strlen_zero(args->orig_chan_name) || !strcasecmp(peer->name, args->orig_chan_name))) {
795                 /* 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. */
796                 ast_set_flag(peer, AST_FLAG_MASQ_NOSTREAM);
797                 /* Tell the peer channel the number of the parking space */
798                 ast_say_digits(peer, pu->parkingnum, "", peer->language);
799                 ast_clear_flag(peer, AST_FLAG_MASQ_NOSTREAM);
800         }
801         if (peer == chan) { /* pu->notquiteyet = 1 */
802                 /* Wake up parking thread if we're really done */
803                 ast_indicate_data(pu->chan, AST_CONTROL_HOLD, 
804                         S_OR(pu->parkinglot->mohclass, NULL),
805                         !ast_strlen_zero(pu->parkinglot->mohclass) ? strlen(pu->parkinglot->mohclass) + 1 : 0);
806                 pu->notquiteyet = 0;
807                 pthread_kill(parking_thread, SIGURG);
808         }
809         return 0;
810 }
811
812 /*! \brief Park a call */
813 int ast_park_call(struct ast_channel *chan, struct ast_channel *peer, int timeout, int *extout)
814 {
815         struct ast_park_call_args args = {
816                 .timeout = timeout,
817                 .extout = extout,
818         };
819
820         return park_call_full(chan, peer, &args);
821 }
822
823 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)
824 {
825         struct ast_channel *chan;
826         struct ast_frame *f;
827         int park_status;
828         struct ast_park_call_args park_args = {0,};
829
830         if (!args) {
831                 args = &park_args;
832                 args->timeout = timeout;
833                 args->extout = extout;
834         }
835
836         if ((args->pu = park_space_reserve(rchan, peer, args)) == NULL) {
837                 if (peer)
838                         ast_stream_and_wait(peer, "beeperr", "");
839                 return AST_FEATURE_RETURN_PARKFAILED;
840         }
841
842         /* Make a new, fake channel that we'll use to masquerade in the real one */
843         if (!(chan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, rchan->accountcode, rchan->exten, rchan->context, rchan->amaflags, "Parked/%s",rchan->name))) {
844                 ast_log(LOG_WARNING, "Unable to create parked channel\n");
845                 return -1;
846         }
847
848         /* Make formats okay */
849         chan->readformat = rchan->readformat;
850         chan->writeformat = rchan->writeformat;
851         ast_channel_masquerade(chan, rchan);
852
853         /* Setup the extensions and such */
854         set_c_e_p(chan, rchan->context, rchan->exten, rchan->priority);
855
856         /* Make the masq execute */
857         if ((f = ast_read(chan)))
858                 ast_frfree(f);
859
860         if (peer == rchan) {
861                 peer = chan;
862         }
863
864         if (!play_announcement && args == &park_args) {
865                 args->orig_chan_name = ast_strdupa(chan->name);
866         }
867
868         park_status = park_call_full(chan, peer, args);
869         if (park_status == 1) {
870         /* would be nice to play "invalid parking extension" */
871                 ast_hangup(chan);
872                 return -1;
873         }
874
875         return 0;
876 }
877
878 /* Park call via masquraded channel */
879 int ast_masq_park_call(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
880 {
881         return masq_park_call(rchan, peer, timeout, extout, 0, NULL);
882 }
883
884 static int masq_park_call_announce_args(struct ast_channel *rchan, struct ast_channel *peer, struct ast_park_call_args *args)
885 {
886         return masq_park_call(rchan, peer, 0, NULL, 1, args);
887 }
888
889 static int masq_park_call_announce(struct ast_channel *rchan, struct ast_channel *peer, int timeout, int *extout)
890 {
891         return masq_park_call(rchan, peer, timeout, extout, 1, NULL);
892 }
893
894 /*! 
895  * \brief set caller and callee according to the direction 
896  * \param caller, callee, peer, chan, sense
897  *
898  * Detect who triggered feature and set callee/caller variables accordingly
899 */
900 static void set_peers(struct ast_channel **caller, struct ast_channel **callee,
901         struct ast_channel *peer, struct ast_channel *chan, int sense)
902 {
903         if (sense == FEATURE_SENSE_PEER) {
904                 *caller = peer;
905                 *callee = chan;
906         } else {
907                 *callee = peer;
908                 *caller = chan;
909         }
910 }
911
912 /*! 
913  * \brief support routing for one touch call parking
914  * \param chan channel parking call
915  * \param peer channel to be parked
916  * \param config unsed
917  * \param code unused
918  * \param sense feature options
919  *
920  * \param data
921  * Setup channel, set return exten,priority to 's,1'
922  * answer chan, sleep chan, park call
923 */
924 static int builtin_parkcall(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
925 {
926         struct ast_channel *parker;
927         struct ast_channel *parkee;
928         int res = 0;
929
930         set_peers(&parker, &parkee, peer, chan, sense);
931         /* we used to set chan's exten and priority to "s" and 1
932            here, but this generates (in some cases) an invalid
933            extension, and if "s" exists, could errantly
934            cause execution of extensions you don't expect. It
935            makes more sense to let nature take its course
936            when chan finishes, and let the pbx do its thing
937            and hang up when the park is over.
938         */
939         if (chan->_state != AST_STATE_UP)
940                 res = ast_answer(chan);
941         if (!res)
942                 res = ast_safe_sleep(chan, 1000);
943
944         if (!res) { /* one direction used to call park_call.... */
945                 res = masq_park_call_announce(parkee, parker, 0, NULL);
946                 /* PBX should hangup zombie channel if a masquerade actually occurred (res=0) */
947         }
948
949         return res;
950 }
951
952 /*! \brief Play message to both caller and callee in bridged call, plays synchronously, autoservicing the
953         other channel during the message, so please don't use this for very long messages
954  */
955 static int play_message_in_bridged_call(struct ast_channel *caller_chan, struct ast_channel *callee_chan, const char *audiofile)
956 {
957         /* First play for caller, put other channel on auto service */
958         if (ast_autoservice_start(callee_chan))
959                 return -1;
960         if (ast_stream_and_wait(caller_chan, audiofile, "")) {
961                 ast_log(LOG_WARNING, "Failed to play automon message!\n");
962                 ast_autoservice_stop(callee_chan);
963                 return -1;
964         }
965         if (ast_autoservice_stop(callee_chan))
966                 return -1;
967         /* Then play for callee, put other channel on auto service */
968         if (ast_autoservice_start(caller_chan))
969                 return -1;
970         if (ast_stream_and_wait(callee_chan, audiofile, "")) {
971                 ast_log(LOG_WARNING, "Failed to play automon message !\n");
972                 ast_autoservice_stop(caller_chan);
973                 return -1;
974         }
975         if (ast_autoservice_stop(caller_chan))
976                 return -1;
977         return(0);
978 }
979
980 /*!
981  * \brief Monitor a channel by DTMF
982  * \param chan channel requesting monitor
983  * \param peer channel to be monitored
984  * \param config
985  * \param code
986  * \param sense feature options
987  *
988  * \param data
989  * Check monitor app enabled, setup channels, both caller/callee chans not null
990  * get TOUCH_MONITOR variable for filename if exists, exec monitor app.
991  * \retval AST_FEATURE_RETURN_SUCCESS on success.
992  * \retval -1 on error.
993 */
994 static int builtin_automonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
995 {
996         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
997         int x = 0;
998         size_t len;
999         struct ast_channel *caller_chan, *callee_chan;
1000         const char *automon_message_start = NULL;
1001         const char *automon_message_stop = NULL;
1002
1003         if (!monitor_ok) {
1004                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1005                 return -1;
1006         }
1007
1008         if (!monitor_app && !(monitor_app = pbx_findapp("Monitor"))) {
1009                 monitor_ok = 0;
1010                 ast_log(LOG_ERROR,"Cannot record the call. The monitor application is disabled.\n");
1011                 return -1;
1012         }
1013
1014         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1015         if (caller_chan) {      /* Find extra messages */
1016                 automon_message_start = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_START");
1017                 automon_message_stop = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_MESSAGE_STOP");
1018         }
1019
1020         if (!ast_strlen_zero(courtesytone)) {   /* Play courtesy tone if configured */
1021                 if(play_message_in_bridged_call(caller_chan, callee_chan, courtesytone) == -1) {
1022                         return -1;
1023                 }
1024         }
1025         
1026         if (callee_chan->monitor) {
1027                 ast_verb(4, "User hit '%s' to stop recording call.\n", code);
1028                 if (!ast_strlen_zero(automon_message_stop)) {
1029                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_stop);
1030                 }
1031                 callee_chan->monitor->stop(callee_chan, 1);
1032                 return AST_FEATURE_RETURN_SUCCESS;
1033         }
1034
1035         if (caller_chan && callee_chan) {
1036                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_FORMAT");
1037                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR");
1038                 const char *touch_monitor_prefix = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MONITOR_PREFIX");
1039
1040                 if (!touch_format)
1041                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_FORMAT");
1042
1043                 if (!touch_monitor)
1044                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR");
1045         
1046                 if (!touch_monitor_prefix)
1047                         touch_monitor_prefix = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MONITOR_PREFIX");
1048         
1049                 if (touch_monitor) {
1050                         len = strlen(touch_monitor) + 50;
1051                         args = alloca(len);
1052                         touch_filename = alloca(len);
1053                         snprintf(touch_filename, len, "%s-%ld-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), touch_monitor);
1054                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1055                 } else {
1056                         caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
1057                         callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
1058                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1059                         args = alloca(len);
1060                         touch_filename = alloca(len);
1061                         snprintf(touch_filename, len, "%s-%ld-%s-%s", S_OR(touch_monitor_prefix, "auto"), (long)time(NULL), caller_chan_id, callee_chan_id);
1062                         snprintf(args, len, "%s,%s,m", S_OR(touch_format, "wav"), touch_filename);
1063                 }
1064
1065                 for(x = 0; x < strlen(args); x++) {
1066                         if (args[x] == '/')
1067                                 args[x] = '-';
1068                 }
1069                 
1070                 ast_verb(4, "User hit '%s' to record call. filename: %s\n", code, args);
1071
1072                 pbx_exec(callee_chan, monitor_app, args);
1073                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1074                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MONITOR_OUTPUT", touch_filename);
1075
1076                 if (!ast_strlen_zero(automon_message_start)) {  /* Play start message for both channels */
1077                         play_message_in_bridged_call(caller_chan, callee_chan, automon_message_start);
1078                 }
1079         
1080                 return AST_FEATURE_RETURN_SUCCESS;
1081         }
1082         
1083         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");   
1084         return -1;
1085 }
1086
1087 static int builtin_automixmonitor(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1088 {
1089         char *caller_chan_id = NULL, *callee_chan_id = NULL, *args = NULL, *touch_filename = NULL;
1090         int x = 0;
1091         size_t len;
1092         struct ast_channel *caller_chan, *callee_chan;
1093         const char *mixmonitor_spy_type = "MixMonitor";
1094         int count = 0;
1095
1096         if (!mixmonitor_ok) {
1097                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1098                 return -1;
1099         }
1100
1101         if (!(mixmonitor_app = pbx_findapp("MixMonitor"))) {
1102                 mixmonitor_ok = 0;
1103                 ast_log(LOG_ERROR,"Cannot record the call. The mixmonitor application is disabled.\n");
1104                 return -1;
1105         }
1106
1107         set_peers(&caller_chan, &callee_chan, peer, chan, sense);
1108
1109         if (!ast_strlen_zero(courtesytone)) {
1110                 if (ast_autoservice_start(callee_chan))
1111                         return -1;
1112                 if (ast_stream_and_wait(caller_chan, courtesytone, "")) {
1113                         ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
1114                         ast_autoservice_stop(callee_chan);
1115                         return -1;
1116                 }
1117                 if (ast_autoservice_stop(callee_chan))
1118                         return -1;
1119         }
1120
1121         ast_channel_lock(callee_chan);
1122         count = ast_channel_audiohook_count_by_source(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1123         ast_channel_unlock(callee_chan);
1124
1125         /* This means a mixmonitor is attached to the channel, running or not is unknown. */
1126         if (count > 0) {
1127                 
1128                 ast_verb(3, "User hit '%s' to stop recording call.\n", code);
1129
1130                 /* Make sure they are running */
1131                 ast_channel_lock(callee_chan);
1132                 count = ast_channel_audiohook_count_by_source_running(callee_chan, mixmonitor_spy_type, AST_AUDIOHOOK_TYPE_SPY);
1133                 ast_channel_unlock(callee_chan);
1134                 if (count > 0) {
1135                         if (!stopmixmonitor_ok) {
1136                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1137                                 return -1;
1138                         }
1139                         if (!(stopmixmonitor_app = pbx_findapp("StopMixMonitor"))) {
1140                                 stopmixmonitor_ok = 0;
1141                                 ast_log(LOG_ERROR,"Cannot stop recording the call. The stopmixmonitor application is disabled.\n");
1142                                 return -1;
1143                         } else {
1144                                 pbx_exec(callee_chan, stopmixmonitor_app, "");
1145                                 return AST_FEATURE_RETURN_SUCCESS;
1146                         }
1147                 }
1148                 
1149                 ast_log(LOG_WARNING,"Stopped MixMonitors are attached to the channel.\n");      
1150         }                       
1151
1152         if (caller_chan && callee_chan) {
1153                 const char *touch_format = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR_FORMAT");
1154                 const char *touch_monitor = pbx_builtin_getvar_helper(caller_chan, "TOUCH_MIXMONITOR");
1155
1156                 if (!touch_format)
1157                         touch_format = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR_FORMAT");
1158
1159                 if (!touch_monitor)
1160                         touch_monitor = pbx_builtin_getvar_helper(callee_chan, "TOUCH_MIXMONITOR");
1161
1162                 if (touch_monitor) {
1163                         len = strlen(touch_monitor) + 50;
1164                         args = alloca(len);
1165                         touch_filename = alloca(len);
1166                         snprintf(touch_filename, len, "auto-%ld-%s", (long)time(NULL), touch_monitor);
1167                         snprintf(args, len, "%s.%s,b", touch_filename, (touch_format) ? touch_format : "wav");
1168                 } else {
1169                         caller_chan_id = ast_strdupa(S_OR(caller_chan->cid.cid_num, caller_chan->name));
1170                         callee_chan_id = ast_strdupa(S_OR(callee_chan->cid.cid_num, callee_chan->name));
1171                         len = strlen(caller_chan_id) + strlen(callee_chan_id) + 50;
1172                         args = alloca(len);
1173                         touch_filename = alloca(len);
1174                         snprintf(touch_filename, len, "auto-%ld-%s-%s", (long)time(NULL), caller_chan_id, callee_chan_id);
1175                         snprintf(args, len, "%s.%s,b", touch_filename, S_OR(touch_format, "wav"));
1176                 }
1177
1178                 for( x = 0; x < strlen(args); x++) {
1179                         if (args[x] == '/')
1180                                 args[x] = '-';
1181                 }
1182
1183                 ast_verb(3, "User hit '%s' to record call. filename: %s\n", code, touch_filename);
1184
1185                 pbx_exec(callee_chan, mixmonitor_app, args);
1186                 pbx_builtin_setvar_helper(callee_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1187                 pbx_builtin_setvar_helper(caller_chan, "TOUCH_MIXMONITOR_OUTPUT", touch_filename);
1188                 return AST_FEATURE_RETURN_SUCCESS;
1189         
1190         }
1191
1192         ast_log(LOG_NOTICE,"Cannot record the call. One or both channels have gone away.\n");
1193         return -1;
1194
1195 }
1196
1197 static int builtin_disconnect(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1198 {
1199         ast_verb(4, "User hit '%s' to disconnect call.\n", code);
1200         return AST_FEATURE_RETURN_HANGUP;
1201 }
1202
1203 static int finishup(struct ast_channel *chan)
1204 {
1205         ast_indicate(chan, AST_CONTROL_UNHOLD);
1206
1207         return ast_autoservice_stop(chan);
1208 }
1209
1210 /*!
1211  * \brief Find the context for the transfer
1212  * \param transferer
1213  * \param transferee
1214  * 
1215  * Grab the TRANSFER_CONTEXT, if fails try grabbing macrocontext.
1216  * \return a context string
1217 */
1218 static const char *real_ctx(struct ast_channel *transferer, struct ast_channel *transferee)
1219 {
1220         const char *s = pbx_builtin_getvar_helper(transferer, "TRANSFER_CONTEXT");
1221         if (ast_strlen_zero(s)) {
1222                 s = pbx_builtin_getvar_helper(transferee, "TRANSFER_CONTEXT");
1223         }
1224         if (ast_strlen_zero(s)) { /* Use the non-macro context to transfer the call XXX ? */
1225                 s = transferer->macrocontext;
1226         }
1227         if (ast_strlen_zero(s)) {
1228                 s = transferer->context;
1229         }
1230         return s;  
1231 }
1232
1233 /*!
1234  * \brief Blind transfer user to another extension
1235  * \param chan channel to be transfered
1236  * \param peer channel initiated blind transfer
1237  * \param config
1238  * \param code
1239  * \param data
1240  * \param sense  feature options
1241  * 
1242  * Place chan on hold, check if transferred to parkinglot extension,
1243  * otherwise check extension exists and transfer caller.
1244  * \retval AST_FEATURE_RETURN_SUCCESS.
1245  * \retval -1 on failure.
1246 */
1247 static int builtin_blindtransfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1248 {
1249         struct ast_channel *transferer;
1250         struct ast_channel *transferee;
1251         const char *transferer_real_context;
1252         char xferto[256];
1253         int res, parkstatus = 0;
1254
1255         set_peers(&transferer, &transferee, peer, chan, sense);
1256         transferer_real_context = real_ctx(transferer, transferee);
1257         /* Start autoservice on chan while we talk to the originator */
1258         ast_autoservice_start(transferee);
1259         ast_indicate(transferee, AST_CONTROL_HOLD);
1260
1261         memset(xferto, 0, sizeof(xferto));
1262
1263         /* Transfer */
1264         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1265         if (res < 0) {
1266                 finishup(transferee);
1267                 return -1; /* error ? */
1268         }
1269         if (res > 0)    /* If they've typed a digit already, handle it */
1270                 xferto[0] = (char) res;
1271
1272         ast_stopstream(transferer);
1273         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1274         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
1275                 finishup(transferee);
1276                 return res;
1277         }
1278         if (!strcmp(xferto, ast_parking_ext())) {
1279                 res = finishup(transferee);
1280                 if (res)
1281                         res = -1;
1282                 else if (!(parkstatus = masq_park_call_announce(transferee, transferer, 0, NULL))) {    /* success */
1283                         /* We return non-zero, but tell the PBX not to hang the channel when
1284                            the thread dies -- We have to be careful now though.  We are responsible for 
1285                            hanging up the channel, else it will never be hung up! */
1286
1287                         return 0;
1288                 } else {
1289                         ast_log(LOG_WARNING, "Unable to park call %s, parkstatus = %d\n", transferee->name, parkstatus);
1290                 }
1291                 /*! \todo XXX Maybe we should have another message here instead of invalid extension XXX */
1292         } else if (ast_exists_extension(transferee, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
1293                 pbx_builtin_setvar_helper(transferer, "BLINDTRANSFER", transferee->name);
1294                 pbx_builtin_setvar_helper(transferee, "BLINDTRANSFER", transferer->name);
1295                 res=finishup(transferee);
1296                 if (!transferer->cdr) { /* this code should never get called (in a perfect world) */
1297                         transferer->cdr=ast_cdr_alloc();
1298                         if (transferer->cdr) {
1299                                 ast_cdr_init(transferer->cdr, transferer); /* initilize our channel's cdr */
1300                                 ast_cdr_start(transferer->cdr);
1301                         }
1302                 }
1303                 if (transferer->cdr) {
1304                         struct ast_cdr *swap = transferer->cdr;
1305                         ast_log(LOG_DEBUG,"transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
1306                                         transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
1307                                         transferer->cdr->channel, transferer->cdr->dstchannel);
1308                         ast_log(LOG_DEBUG,"TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
1309                                         transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
1310                         ast_log(LOG_DEBUG,"transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
1311                         /* swap cdrs-- it will save us some time & work */
1312                         transferer->cdr = transferee->cdr;
1313                         transferee->cdr = swap;
1314                 }
1315                 if (!transferee->pbx) {
1316                         /* Doh!  Use our handy async_goto functions */
1317                         ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
1318                                                                 ,transferee->name, xferto, transferer_real_context);
1319                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
1320                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
1321                 } else {
1322                         /* Set the channel's new extension, since it exists, using transferer context */
1323                         ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
1324                         ast_log(LOG_DEBUG,"ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
1325                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
1326                 }
1327                 check_goto_on_transfer(transferer);
1328                 return res;
1329         } else {
1330                 ast_verb(3, "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
1331         }
1332         if (parkstatus != AST_FEATURE_RETURN_PARKFAILED && ast_stream_and_wait(transferer, xferfailsound, AST_DIGIT_ANY) < 0) {
1333                 finishup(transferee);
1334                 return -1;
1335         }
1336         ast_stopstream(transferer);
1337         res = finishup(transferee);
1338         if (res) {
1339                 ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
1340                 return res;
1341         }
1342         return AST_FEATURE_RETURN_SUCCESS;
1343 }
1344
1345 /*!
1346  * \brief make channels compatible
1347  * \param c
1348  * \param newchan
1349  * \retval 0 on success.
1350  * \retval -1 on failure.
1351 */
1352 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
1353 {
1354         if (ast_channel_make_compatible(c, newchan) < 0) {
1355                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
1356                         c->name, newchan->name);
1357                 ast_hangup(newchan);
1358                 return -1;
1359         }
1360         return 0;
1361 }
1362
1363 /*!
1364  * \brief Attended transfer
1365  * \param chan transfered user
1366  * \param peer person transfering call
1367  * \param config
1368  * \param code
1369  * \param sense feature options
1370  * 
1371  * \param data
1372  * Get extension to transfer to, if you cannot generate channel (or find extension) 
1373  * return to host channel. After called channel answered wait for hangup of transferer,
1374  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
1375  *
1376  * \return -1 on failure
1377 */
1378 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1379 {
1380         struct ast_channel *transferer;
1381         struct ast_channel *transferee;
1382         const char *transferer_real_context;
1383         char xferto[256] = "";
1384         int res;
1385         int outstate=0;
1386         struct ast_channel *newchan;
1387         struct ast_channel *xferchan;
1388         struct ast_bridge_thread_obj *tobj;
1389         struct ast_bridge_config bconfig;
1390         struct ast_frame *f;
1391         int l;
1392         struct ast_party_connected_line connected_line;
1393         struct ast_datastore *features_datastore;
1394         struct ast_dial_features *dialfeatures = NULL;
1395
1396         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
1397         set_peers(&transferer, &transferee, peer, chan, sense);
1398         transferer_real_context = real_ctx(transferer, transferee);
1399         /* Start autoservice on chan while we talk to the originator */
1400         ast_autoservice_start(transferee);
1401         ast_indicate(transferee, AST_CONTROL_HOLD);
1402         
1403         /* Transfer */
1404         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1405         if (res < 0) {
1406                 finishup(transferee);
1407                 return res;
1408         }
1409         if (res > 0) /* If they've typed a digit already, handle it */
1410                 xferto[0] = (char) res;
1411
1412         /* this is specific of atxfer */
1413         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1414         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
1415                 finishup(transferee);
1416                 return res;
1417         }
1418         if (res == 0) {
1419                 ast_log(LOG_WARNING, "Did not read data.\n");
1420                 finishup(transferee);
1421                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1422                         return -1;
1423                 return AST_FEATURE_RETURN_SUCCESS;
1424         }
1425
1426         /* valid extension, res == 1 */
1427         if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
1428                 ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
1429                 finishup(transferee);
1430                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1431                         return -1;
1432                 return AST_FEATURE_RETURN_SUCCESS;
1433         }
1434
1435         /* If we are attended transfering to parking, just use builtin_parkcall instead of trying to track all of
1436          * the different variables for handling this properly with a builtin_atxfer */
1437         if (!strcmp(xferto, ast_parking_ext())) {
1438                 finishup(transferee);
1439                 return builtin_parkcall(chan, peer, config, code, sense, data);
1440         }
1441
1442         l = strlen(xferto);
1443         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);     /* append context */
1444
1445         /* If we are performing an attended transfer and we have two channels involved then
1446            copy sound file information to play upon attended transfer completion */
1447         if (transferee) {
1448                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1449                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1450
1451                 if (!ast_strlen_zero(chan1_attended_sound)) {
1452                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
1453                 }
1454                 if (!ast_strlen_zero(chan2_attended_sound)) {
1455                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
1456                 }
1457         }
1458
1459         newchan = feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
1460                 xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
1461
1462         ast_party_connected_line_init(&connected_line);
1463         if (!ast_check_hangup(transferer)) {
1464                 /* Transferer is up - old behaviour */
1465                 ast_indicate(transferer, -1);
1466                 if (!newchan) {
1467                         finishup(transferee);
1468                         /* any reason besides user requested cancel and busy triggers the failed sound */
1469                         if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
1470                                 ast_stream_and_wait(transferer, xferfailsound, ""))
1471                                 return -1;
1472                         if (ast_stream_and_wait(transferer, xfersound, ""))
1473                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1474                         return AST_FEATURE_RETURN_SUCCESS;
1475                 }
1476
1477                 if (check_compat(transferer, newchan)) {
1478                         /* we do mean transferee here, NOT transferer */
1479                         finishup(transferee);
1480                         return -1;
1481                 }
1482                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
1483                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1484                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1485                 /* We need to get the transferer's connected line information copied
1486                  * at this point because he is likely to hang up during the bridge with
1487                  * newchan. This info will be used down below before bridging the 
1488                  * transferee and newchan
1489                  *
1490                  * As a result, we need to be sure to free this data before returning
1491                  * or overwriting it.
1492                  */
1493                 ast_channel_lock(transferer);
1494                 ast_party_connected_line_copy(&connected_line, &transferer->connected);
1495                 ast_channel_unlock(transferer);
1496                 res = ast_bridge_call(transferer, newchan, &bconfig);
1497                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
1498                         ast_hangup(newchan);
1499                         if (ast_stream_and_wait(transferer, xfersound, ""))
1500                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1501                         finishup(transferee);
1502                         transferer->_softhangup = 0;
1503                         ast_party_connected_line_free(&connected_line);
1504                         return AST_FEATURE_RETURN_SUCCESS;
1505                 }
1506                 if (check_compat(transferee, newchan)) {
1507                         finishup(transferee);
1508                         ast_party_connected_line_free(&connected_line);
1509                         return -1;
1510                 }
1511                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
1512
1513                 if ((ast_autoservice_stop(transferee) < 0)
1514                  || (ast_waitfordigit(transferee, 100) < 0)
1515                  || (ast_waitfordigit(newchan, 100) < 0)
1516                  || ast_check_hangup(transferee)
1517                  || ast_check_hangup(newchan)) {
1518                         ast_hangup(newchan);
1519                         ast_party_connected_line_free(&connected_line);
1520                         return -1;
1521                 }
1522                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Transfered/%s", transferee->name);
1523                 if (!xferchan) {
1524                         ast_hangup(newchan);
1525                         ast_party_connected_line_free(&connected_line);
1526                         return -1;
1527                 }
1528                 /* Make formats okay */
1529                 xferchan->visible_indication = transferer->visible_indication;
1530                 xferchan->readformat = transferee->readformat;
1531                 xferchan->writeformat = transferee->writeformat;
1532                 ast_channel_masquerade(xferchan, transferee);
1533                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
1534                 xferchan->_state = AST_STATE_UP;
1535                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
1536                 xferchan->_softhangup = 0;
1537                 if ((f = ast_read(xferchan)))
1538                         ast_frfree(f);
1539                 newchan->_state = AST_STATE_UP;
1540                 ast_clear_flag(newchan, AST_FLAGS_ALL);
1541                 newchan->_softhangup = 0;
1542                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
1543                         ast_hangup(xferchan);
1544                         ast_hangup(newchan);
1545                         ast_party_connected_line_free(&connected_line);
1546                         return -1;
1547                 }
1548
1549                 ast_channel_lock(newchan);
1550                 if ((features_datastore = ast_channel_datastore_find(newchan, &dial_features_info, NULL))) {
1551                                 dialfeatures = features_datastore->data;
1552                 }
1553                 ast_channel_unlock(newchan);
1554
1555                 if (dialfeatures) {
1556                         /* newchan should always be the callee and shows up as callee in dialfeatures, but for some reason
1557                            I don't currently understand, the abilities of newchan seem to be stored on the caller side */
1558                         ast_copy_flags(&(config->features_callee), &(dialfeatures->features_caller), AST_FLAGS_ALL);
1559                         dialfeatures = NULL;
1560                 }
1561
1562                 ast_channel_lock(xferchan);
1563                 if ((features_datastore = ast_channel_datastore_find(xferchan, &dial_features_info, NULL))) {
1564                         dialfeatures = features_datastore->data;
1565                 }
1566                 ast_channel_unlock(xferchan);
1567          
1568                 if (dialfeatures) {
1569                         ast_copy_flags(&(config->features_caller), &(dialfeatures->features_caller), AST_FLAGS_ALL);
1570                 }
1571          
1572                 tobj->chan = newchan;
1573                 tobj->peer = xferchan;
1574                 tobj->bconfig = *config;
1575
1576                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
1577                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
1578                 }
1579
1580                 /* Due to a limitation regarding when callerID is set on a Local channel,
1581                  * we use the transferer's connected line information here.
1582                  */
1583                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1584                 ast_channel_update_connected_line(xferchan, &connected_line);
1585                 ast_channel_lock(xferchan);
1586                 ast_connected_line_copy_from_caller(&connected_line, &xferchan->cid);
1587                 ast_channel_unlock(xferchan);
1588                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1589                 ast_channel_update_connected_line(newchan, &connected_line);
1590                 ast_party_connected_line_free(&connected_line);
1591
1592                 if (ast_stream_and_wait(newchan, xfersound, ""))
1593                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1594                 bridge_call_thread_launch(tobj);
1595                 return -1;      /* XXX meaning the channel is bridged ? */
1596         } else if (!ast_check_hangup(transferee)) {
1597                 /* act as blind transfer */
1598                 if (ast_autoservice_stop(transferee) < 0) {
1599                         ast_hangup(newchan);
1600                         return -1;
1601                 }
1602
1603                 if (!newchan) {
1604                         unsigned int tries = 0;
1605                         char *transferer_tech, *transferer_name = ast_strdupa(transferer->name);
1606
1607                         transferer_tech = strsep(&transferer_name, "/");
1608                         transferer_name = strsep(&transferer_name, "-");
1609
1610                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
1611                                 ast_log(LOG_WARNING, "Transferer has invalid channel name: '%s'\n", transferer->name);
1612                                 if (ast_stream_and_wait(transferee, "beeperr", ""))
1613                                         return -1;
1614                                 return AST_FEATURE_RETURN_SUCCESS;
1615                         }
1616
1617                         ast_log(LOG_NOTICE, "We're trying to call %s/%s\n", transferer_tech, transferer_name);
1618                         newchan = feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
1619                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
1620                         while (!newchan && !atxferdropcall && tries < atxfercallbackretries) {
1621                                 /* Trying to transfer again */
1622                                 ast_autoservice_start(transferee);
1623                                 ast_indicate(transferee, AST_CONTROL_HOLD);
1624
1625                                 newchan = feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
1626                                         xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
1627                                 if (ast_autoservice_stop(transferee) < 0) {
1628                                         if (newchan)
1629                                                 ast_hangup(newchan);
1630                                         return -1;
1631                                 }
1632                                 if (!newchan) {
1633                                         /* Transfer failed, sleeping */
1634                                         ast_debug(1, "Sleeping for %d ms before callback.\n", atxferloopdelay);
1635                                         ast_safe_sleep(transferee, atxferloopdelay);
1636                                         ast_debug(1, "Trying to callback...\n");
1637                                         newchan = feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
1638                                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
1639                                 }
1640                                 tries++;
1641                         }
1642                 }
1643                 if (!newchan)
1644                         return -1;
1645
1646                 /* newchan is up, we should prepare transferee and bridge them */
1647                 if (check_compat(transferee, newchan)) {
1648                         finishup(transferee);
1649                         return -1;
1650                 }
1651                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
1652
1653                 if ((ast_waitfordigit(transferee, 100) < 0)
1654                    || (ast_waitfordigit(newchan, 100) < 0)
1655                    || ast_check_hangup(transferee)
1656                    || ast_check_hangup(newchan)) {
1657                         ast_hangup(newchan);
1658                         return -1;
1659                 }
1660
1661                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Transfered/%s", transferee->name);
1662                 if (!xferchan) {
1663                         ast_hangup(newchan);
1664                         return -1;
1665                 }
1666                 /* Make formats okay */
1667                 xferchan->visible_indication = transferer->visible_indication;
1668                 xferchan->readformat = transferee->readformat;
1669                 xferchan->writeformat = transferee->writeformat;
1670                 ast_channel_masquerade(xferchan, transferee);
1671                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
1672                 xferchan->_state = AST_STATE_UP;
1673                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
1674                 xferchan->_softhangup = 0;
1675                 if ((f = ast_read(xferchan)))
1676                         ast_frfree(f);
1677                 newchan->_state = AST_STATE_UP;
1678                 ast_clear_flag(newchan, AST_FLAGS_ALL);
1679                 newchan->_softhangup = 0;
1680                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
1681                         ast_hangup(xferchan);
1682                         ast_hangup(newchan);
1683                         return -1;
1684                 }
1685                 tobj->chan = newchan;
1686                 tobj->peer = xferchan;
1687                 tobj->bconfig = *config;
1688                 
1689                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
1690                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
1691                 }
1692
1693                 ast_channel_lock(newchan);
1694                 ast_connected_line_copy_from_caller(&connected_line, &newchan->cid);
1695                 ast_channel_unlock(newchan);
1696                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1697                 ast_channel_update_connected_line(xferchan, &connected_line);
1698                 ast_channel_lock(xferchan);
1699                 ast_connected_line_copy_from_caller(&connected_line, &xferchan->cid);
1700                 ast_channel_unlock(xferchan);
1701                 connected_line.source = AST_CONNECTED_LINE_UPDATE_SOURCE_TRANSFER;
1702                 ast_channel_update_connected_line(newchan, &connected_line);
1703
1704                 ast_party_connected_line_free(&connected_line);
1705                 
1706                 if (ast_stream_and_wait(newchan, xfersound, ""))
1707                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1708                 bridge_call_thread_launch(tobj);
1709                 return -1;      /* XXX meaning the channel is bridged ? */
1710         } else {
1711                 /* Transferee hung up */
1712                 finishup(transferee);
1713                 return -1;
1714         }
1715 }
1716
1717 /* add atxfer and automon as undefined so you can only use em if you configure them */
1718 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
1719
1720 AST_RWLOCK_DEFINE_STATIC(features_lock);
1721
1722 static struct ast_call_feature builtin_features[] = 
1723 {
1724         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1725         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1726         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1727         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1728         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1729         { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1730 };
1731
1732
1733 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
1734
1735 /*! \brief register new feature into feature_list*/
1736 void ast_register_feature(struct ast_call_feature *feature)
1737 {
1738         if (!feature) {
1739                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
1740                 return;
1741         }
1742   
1743         AST_RWLIST_WRLOCK(&feature_list);
1744         AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
1745         AST_RWLIST_UNLOCK(&feature_list);
1746
1747         ast_verb(2, "Registered Feature '%s'\n",feature->sname);
1748 }
1749
1750 /*! 
1751  * \brief Add new feature group
1752  * \param fgname feature group name.
1753  *
1754  * Add new feature group to the feature group list insert at head of list.
1755  * \note This function MUST be called while feature_groups is locked.
1756 */
1757 static struct feature_group* register_group(const char *fgname)
1758 {
1759         struct feature_group *fg;
1760
1761         if (!fgname) {
1762                 ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
1763                 return NULL;
1764         }
1765
1766         if (!(fg = ast_calloc(1, sizeof(*fg))))
1767                 return NULL;
1768
1769         if (ast_string_field_init(fg, 128)) {
1770                 ast_free(fg);
1771                 return NULL;
1772         }
1773
1774         ast_string_field_set(fg, gname, fgname);
1775
1776         AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
1777
1778         ast_verb(2, "Registered group '%s'\n", fg->gname);
1779
1780         return fg;
1781 }
1782
1783 /*! 
1784  * \brief Add feature to group
1785  * \param fg feature group
1786  * \param exten
1787  * \param feature feature to add.
1788  *
1789  * Check fg and feature specified, add feature to list
1790  * \note This function MUST be called while feature_groups is locked. 
1791 */
1792 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature) 
1793 {
1794         struct feature_group_exten *fge;
1795
1796         if (!fg) {
1797                 ast_log(LOG_NOTICE, "You didn't pass a group!\n");
1798                 return;
1799         }
1800
1801         if (!feature) {
1802                 ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
1803                 return;
1804         }
1805
1806         if (!(fge = ast_calloc(1, sizeof(*fge))))
1807                 return;
1808
1809         if (ast_string_field_init(fge, 128)) {
1810                 ast_free(fge);
1811                 return;
1812         }
1813
1814         ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
1815
1816         fge->feature = feature;
1817
1818         AST_LIST_INSERT_HEAD(&fg->features, fge, entry);                
1819
1820         ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
1821                                         feature->sname, fg->gname, exten);
1822 }
1823
1824 void ast_unregister_feature(struct ast_call_feature *feature)
1825 {
1826         if (!feature) {
1827                 return;
1828         }
1829
1830         AST_RWLIST_WRLOCK(&feature_list);
1831         AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
1832         AST_RWLIST_UNLOCK(&feature_list);
1833
1834         ast_free(feature);
1835 }
1836
1837 /*! \brief Remove all features in the list */
1838 static void ast_unregister_features(void)
1839 {
1840         struct ast_call_feature *feature;
1841
1842         AST_RWLIST_WRLOCK(&feature_list);
1843         while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
1844                 ast_free(feature);
1845         }
1846         AST_RWLIST_UNLOCK(&feature_list);
1847 }
1848
1849 /*! \brief find a call feature by name */
1850 static struct ast_call_feature *find_dynamic_feature(const char *name)
1851 {
1852         struct ast_call_feature *tmp;
1853
1854         AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
1855                 if (!strcasecmp(tmp->sname, name)) {
1856                         break;
1857                 }
1858         }
1859
1860         return tmp;
1861 }
1862
1863 /*! \brief Remove all feature groups in the list */
1864 static void ast_unregister_groups(void)
1865 {
1866         struct feature_group *fg;
1867         struct feature_group_exten *fge;
1868
1869         AST_RWLIST_WRLOCK(&feature_groups);
1870         while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
1871                 while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
1872                         ast_string_field_free_memory(fge);
1873                         ast_free(fge);
1874                 }
1875
1876                 ast_string_field_free_memory(fg);
1877                 ast_free(fg);
1878         }
1879         AST_RWLIST_UNLOCK(&feature_groups);
1880 }
1881
1882 /*! 
1883  * \brief Find a group by name 
1884  * \param name feature name
1885  * \retval feature group on success.
1886  * \retval NULL on failure.
1887 */
1888 static struct feature_group *find_group(const char *name) {
1889         struct feature_group *fg = NULL;
1890
1891         AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
1892                 if (!strcasecmp(fg->gname, name))
1893                         break;
1894         }
1895
1896         return fg;
1897 }
1898
1899 void ast_rdlock_call_features(void)
1900 {
1901         ast_rwlock_rdlock(&features_lock);
1902 }
1903
1904 void ast_unlock_call_features(void)
1905 {
1906         ast_rwlock_unlock(&features_lock);
1907 }
1908
1909 struct ast_call_feature *ast_find_call_feature(const char *name)
1910 {
1911         int x;
1912         for (x = 0; x < FEATURES_COUNT; x++) {
1913                 if (!strcasecmp(name, builtin_features[x].sname))
1914                         return &builtin_features[x];
1915         }
1916         return NULL;
1917 }
1918
1919 /*!
1920  * \brief exec an app by feature 
1921  * \param chan,peer,config,code,sense,data
1922  *
1923  * Find a feature, determine which channel activated
1924  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
1925  * \retval -1 error.
1926  * \retval -2 when an application cannot be found.
1927 */
1928 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1929 {
1930         struct ast_app *app;
1931         struct ast_call_feature *feature = data;
1932         struct ast_channel *work, *idle;
1933         int res;
1934
1935         if (!feature) { /* shouldn't ever happen! */
1936                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
1937                 return -1; 
1938         }
1939
1940         if (sense == FEATURE_SENSE_CHAN) {
1941                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
1942                         return AST_FEATURE_RETURN_KEEPTRYING;
1943                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
1944                         work = chan;
1945                         idle = peer;
1946                 } else {
1947                         work = peer;
1948                         idle = chan;
1949                 }
1950         } else {
1951                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
1952                         return AST_FEATURE_RETURN_KEEPTRYING;
1953                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
1954                         work = peer;
1955                         idle = chan;
1956                 } else {
1957                         work = chan;
1958                         idle = peer;
1959                 }
1960         }
1961
1962         if (!(app = pbx_findapp(feature->app))) {
1963                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
1964                 return -2;
1965         }
1966
1967         ast_autoservice_start(idle);
1968         
1969         if (!ast_strlen_zero(feature->moh_class))
1970                 ast_moh_start(idle, feature->moh_class, NULL);
1971
1972         res = pbx_exec(work, app, feature->app_args);
1973
1974         if (!ast_strlen_zero(feature->moh_class))
1975                 ast_moh_stop(idle);
1976
1977         ast_autoservice_stop(idle);
1978
1979         if (res) {
1980                 return AST_FEATURE_RETURN_SUCCESSBREAK;
1981         }
1982         return AST_FEATURE_RETURN_SUCCESS;      /*! \todo XXX should probably return res */
1983 }
1984
1985 static void unmap_features(void)
1986 {
1987         int x;
1988
1989         ast_rwlock_wrlock(&features_lock);
1990         for (x = 0; x < FEATURES_COUNT; x++)
1991                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
1992         ast_rwlock_unlock(&features_lock);
1993 }
1994
1995 static int remap_feature(const char *name, const char *value)
1996 {
1997         int x, res = -1;
1998
1999         ast_rwlock_wrlock(&features_lock);
2000         for (x = 0; x < FEATURES_COUNT; x++) {
2001                 if (strcasecmp(builtin_features[x].sname, name))
2002                         continue;
2003
2004                 ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
2005                 res = 0;
2006                 break;
2007         }
2008         ast_rwlock_unlock(&features_lock);
2009
2010         return res;
2011 }
2012
2013 /*!
2014  * \brief Helper function for feature_interpret and ast_feature_detect
2015  * \param chan,peer,config,code,sense,dynamic_features char buf,feature flags,operation,feature
2016  *
2017  * Lock features list, browse for code, unlock list
2018  * If a feature is found and the operation variable is set, that feature's
2019  * operation is executed.  The first feature found is copied to the feature parameter.
2020  * \retval res on success.
2021  * \retval -1 on failure.
2022 */
2023 static int feature_interpret_helper(struct ast_channel *chan, struct ast_channel *peer,
2024         struct ast_bridge_config *config, char *code, int sense, char *dynamic_features_buf,
2025         struct ast_flags *features, int operation, struct ast_call_feature *feature)
2026 {
2027         int x;
2028         struct feature_group *fg = NULL;
2029         struct feature_group_exten *fge;
2030         struct ast_call_feature *tmpfeature;
2031         char *tmp, *tok;
2032         int res = AST_FEATURE_RETURN_PASSDIGITS;
2033         int feature_detected = 0;
2034
2035         if (!(peer && chan && config) && operation) {
2036                 return -1; /* can not run feature operation */
2037         }
2038
2039         ast_rwlock_rdlock(&features_lock);
2040         for (x = 0; x < FEATURES_COUNT; x++) {
2041                 if ((ast_test_flag(features, builtin_features[x].feature_mask)) &&
2042                     !ast_strlen_zero(builtin_features[x].exten)) {
2043                         /* Feature is up for consideration */
2044                         if (!strcmp(builtin_features[x].exten, code)) {
2045                                 ast_debug(3, "Feature detected: fname=%s sname=%s exten=%s\n", builtin_features[x].fname, builtin_features[x].sname, builtin_features[x].exten);
2046                                 if (operation) {
2047                                         res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
2048                                 }
2049                                 memcpy(feature, &builtin_features[x], sizeof(feature));
2050                                 feature_detected = 1;
2051                                 break;
2052                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
2053                                 if (res == AST_FEATURE_RETURN_PASSDIGITS)
2054                                         res = AST_FEATURE_RETURN_STOREDIGITS;
2055                         }
2056                 }
2057         }
2058         ast_rwlock_unlock(&features_lock);
2059
2060         if (ast_strlen_zero(dynamic_features_buf) || feature_detected) {
2061                 return res;
2062         }
2063
2064         tmp = dynamic_features_buf;
2065
2066         while ((tok = strsep(&tmp, "#"))) {
2067                 AST_RWLIST_RDLOCK(&feature_groups);
2068
2069                 fg = find_group(tok);
2070
2071                 if (fg) {
2072                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
2073                                 if (strcasecmp(fge->exten, code))
2074                                         continue;
2075                                 if (operation) {
2076                                         res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
2077                                 }
2078                                 memcpy(feature, fge->feature, sizeof(feature));
2079                                 if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2080                                         AST_RWLIST_UNLOCK(&feature_groups);
2081                                         break;
2082                                 }
2083                                 res = AST_FEATURE_RETURN_PASSDIGITS;
2084                         }
2085                         if (fge)
2086                                 break;
2087                 }
2088
2089                 AST_RWLIST_UNLOCK(&feature_groups);
2090
2091                 AST_RWLIST_RDLOCK(&feature_list);
2092
2093                 if (!(tmpfeature = find_dynamic_feature(tok))) {
2094                         AST_RWLIST_UNLOCK(&feature_list);
2095                         continue;
2096                 }
2097
2098                 /* Feature is up for consideration */
2099                 if (!strcmp(tmpfeature->exten, code)) {
2100                         ast_verb(3, " Feature Found: %s exten: %s\n",tmpfeature->sname, tok);
2101                         if (operation) {
2102                                 res = tmpfeature->operation(chan, peer, config, code, sense, tmpfeature);
2103                         }
2104                         memcpy(feature, tmpfeature, sizeof(feature));
2105                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
2106                                 AST_RWLIST_UNLOCK(&feature_list);
2107                                 break;
2108                         }
2109                         res = AST_FEATURE_RETURN_PASSDIGITS;
2110                 } else if (!strncmp(tmpfeature->exten, code, strlen(code)))
2111                         res = AST_FEATURE_RETURN_STOREDIGITS;
2112
2113                 AST_RWLIST_UNLOCK(&feature_list);
2114         }
2115
2116         return res;
2117 }
2118
2119 /*!
2120  * \brief Check the dynamic features
2121  * \param chan,peer,config,code,sense
2122  *
2123  * \retval res on success.
2124  * \retval -1 on failure.
2125 */
2126
2127 static int feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense) {
2128
2129         char dynamic_features_buf[128];
2130         const char *peer_dynamic_features, *chan_dynamic_features;
2131         struct ast_flags features;
2132         struct ast_call_feature feature;
2133         if (sense == FEATURE_SENSE_CHAN) {
2134                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
2135         }
2136         else {
2137                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
2138         }
2139
2140         ast_channel_lock(peer);
2141         peer_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES"),""));
2142         ast_channel_unlock(peer);
2143
2144         ast_channel_lock(chan);
2145         chan_dynamic_features = ast_strdupa(S_OR(pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES"),""));
2146         ast_channel_unlock(chan);
2147
2148         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,""));
2149
2150         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);
2151
2152         return feature_interpret_helper(chan, peer, config, code, sense, dynamic_features_buf, &features, 1, &feature);
2153 }
2154
2155
2156 int ast_feature_detect(struct ast_channel *chan, struct ast_flags *features, char *code, struct ast_call_feature *feature) {
2157
2158         return feature_interpret_helper(chan, NULL, NULL, code, 0, NULL, features, 0, feature);
2159 }
2160
2161 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
2162 {
2163         int x;
2164
2165         ast_clear_flag(config, AST_FLAGS_ALL);
2166
2167         ast_rwlock_rdlock(&features_lock);
2168         for (x = 0; x < FEATURES_COUNT; x++) {
2169                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
2170                         continue;
2171
2172                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
2173                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2174
2175                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
2176                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2177         }
2178         ast_rwlock_unlock(&features_lock);
2179
2180         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
2181                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
2182
2183                 if (dynamic_features) {
2184                         char *tmp = ast_strdupa(dynamic_features);
2185                         char *tok;
2186                         struct ast_call_feature *feature;
2187
2188                         /* while we have a feature */
2189                         while ((tok = strsep(&tmp, "#"))) {
2190                                 AST_RWLIST_RDLOCK(&feature_list);
2191                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2192                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2193                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2194                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2195                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2196                                 }
2197                                 AST_RWLIST_UNLOCK(&feature_list);
2198                         }
2199                 }
2200         }
2201 }
2202
2203 /*! 
2204  * \brief Get feature and dial
2205  * \param caller,transferee,type,format,data,timeout,outstate,cid_num,cid_name,igncallerstate
2206  *
2207  * Request channel, set channel variables, initiate call,check if they want to disconnect
2208  * go into loop, check if timeout has elapsed, check if person to be transfered hung up,
2209  * check for answer break loop, set cdr return channel.
2210  *
2211  * \todo XXX Check - this is very similar to the code in channel.c 
2212  * \return always a channel
2213 */
2214 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)
2215 {
2216         int state = 0;
2217         int cause = 0;
2218         int to;
2219         struct ast_channel *chan;
2220         struct ast_channel *monitor_chans[2];
2221         struct ast_channel *active_channel;
2222         int res = 0, ready = 0;
2223         struct timeval started;
2224         int x, len = 0;
2225         char *disconnect_code = NULL, *dialed_code = NULL;
2226
2227         if (!(chan = ast_request(type, format, data, &cause))) {
2228                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2229                 switch(cause) {
2230                 case AST_CAUSE_BUSY:
2231                         state = AST_CONTROL_BUSY;
2232                         break;
2233                 case AST_CAUSE_CONGESTION:
2234                         state = AST_CONTROL_CONGESTION;
2235                         break;
2236                 }
2237                 goto done;
2238         }
2239
2240         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2241         ast_string_field_set(chan, language, language);
2242         ast_channel_inherit_variables(caller, chan);    
2243         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
2244                 
2245         ast_channel_lock(chan);
2246         ast_connected_line_copy_from_caller(&chan->connected, &caller->cid);
2247         ast_channel_unlock(chan);
2248         
2249         if (ast_call(chan, data, timeout)) {
2250                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2251                 goto done;
2252         }
2253         
2254         ast_indicate(caller, AST_CONTROL_RINGING);
2255         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2256         ast_rwlock_rdlock(&features_lock);
2257         for (x = 0; x < FEATURES_COUNT; x++) {
2258                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
2259                         continue;
2260
2261                 disconnect_code = builtin_features[x].exten;
2262                 len = strlen(disconnect_code) + 1;
2263                 dialed_code = alloca(len);
2264                 memset(dialed_code, 0, len);
2265                 break;
2266         }
2267         ast_rwlock_unlock(&features_lock);
2268         x = 0;
2269         started = ast_tvnow();
2270         to = timeout;
2271
2272         ast_poll_channel_add(caller, chan);
2273
2274         while (!((transferee && ast_check_hangup(transferee)) && (!igncallerstate && ast_check_hangup(caller))) && timeout && (chan->_state != AST_STATE_UP)) {
2275                 struct ast_frame *f = NULL;
2276
2277                 monitor_chans[0] = caller;
2278                 monitor_chans[1] = chan;
2279                 active_channel = ast_waitfor_n(monitor_chans, 2, &to);
2280
2281                 /* see if the timeout has been violated */
2282                 if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2283                         state = AST_CONTROL_UNHOLD;
2284                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
2285                         break; /*doh! timeout*/
2286                 }
2287
2288                 if (!active_channel)
2289                         continue;
2290
2291                 if (chan && (chan == active_channel)){
2292                         f = ast_read(chan);
2293                         if (f == NULL) { /*doh! where'd he go?*/
2294                                 state = AST_CONTROL_HANGUP;
2295                                 res = 0;
2296                                 break;
2297                         }
2298                         
2299                         if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
2300                                 if (f->subclass == AST_CONTROL_RINGING) {
2301                                         state = f->subclass;
2302                                         ast_verb(3, "%s is ringing\n", chan->name);
2303                                         ast_indicate(caller, AST_CONTROL_RINGING);
2304                                 } else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2305                                         state = f->subclass;
2306                                         ast_verb(3, "%s is busy\n", chan->name);
2307                                         ast_indicate(caller, AST_CONTROL_BUSY);
2308                                         ast_frfree(f);
2309                                         f = NULL;
2310                                         break;
2311                                 } else if (f->subclass == AST_CONTROL_ANSWER) {
2312                                         /* This is what we are hoping for */
2313                                         state = f->subclass;
2314                                         ast_frfree(f);
2315                                         f = NULL;
2316                                         ready=1;
2317                                         break;
2318                                 } else if (f->subclass == AST_CONTROL_CONNECTED_LINE) {
2319                                         ast_indicate_data(caller, AST_CONTROL_CONNECTED_LINE, f->data.ptr, f->datalen);
2320                                 } else if (f->subclass != -1) {
2321                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass);
2322                                 }
2323                                 /* else who cares */
2324                         }
2325
2326                 } else if (caller && (active_channel == caller)) {
2327                         f = ast_read(caller);
2328                         if (f == NULL) { /*doh! where'd he go?*/
2329                                 if (!igncallerstate) {
2330                                         if (ast_check_hangup(caller) && !ast_check_hangup(chan)) {
2331                                                 /* make this a blind transfer */
2332                                                 ready = 1;
2333                                                 break;
2334                                         }
2335                                         state = AST_CONTROL_HANGUP;
2336                                         res = 0;
2337                                         break;
2338                                 }
2339                         } else {
2340                         
2341                                 if (f->frametype == AST_FRAME_DTMF) {
2342                                         dialed_code[x++] = f->subclass;
2343                                         dialed_code[x] = '\0';
2344                                         if (strlen(dialed_code) == len) {
2345                                                 x = 0;
2346                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
2347                                                 x = 0;
2348                                                 dialed_code[x] = '\0';
2349                                         }
2350                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
2351                                                 /* Caller Canceled the call */
2352                                                 state = AST_CONTROL_UNHOLD;
2353                                                 ast_frfree(f);
2354                                                 f = NULL;
2355                                                 break;
2356                                         }
2357                                 }
2358                         }
2359                 }
2360                 if (f)
2361                         ast_frfree(f);
2362         } /* end while */
2363
2364         ast_poll_channel_del(caller, chan);
2365                 
2366 done:
2367         ast_indicate(caller, -1);
2368         if (chan && ready) {
2369                 if (chan->_state == AST_STATE_UP) 
2370                         state = AST_CONTROL_ANSWER;
2371                 res = 0;
2372         } else if (chan) {
2373                 res = -1;
2374                 ast_hangup(chan);
2375                 chan = NULL;
2376         } else {
2377                 res = -1;
2378         }
2379         
2380         if (outstate)
2381                 *outstate = state;
2382
2383         return chan;
2384 }
2385
2386 /*!
2387  * \brief return the first unlocked cdr in a possible chain
2388 */
2389 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
2390 {
2391         struct ast_cdr *cdr_orig = cdr;
2392         while (cdr) {
2393                 if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
2394                         return cdr;
2395                 cdr = cdr->next;
2396         }
2397         return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
2398 }
2399
2400 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
2401 {
2402         const char *feature;
2403
2404         if (ast_strlen_zero(features)) {
2405                 return;
2406         }
2407
2408         for (feature = features; *feature; feature++) {
2409                 switch (*feature) {
2410                 case 'T' :
2411                 case 't' :
2412                         ast_set_flag(&(config->features_caller), AST_FEATURE_REDIRECT);
2413                         break;
2414                 case 'K' :
2415                 case 'k' :
2416                         ast_set_flag(&(config->features_caller), AST_FEATURE_PARKCALL);
2417                         break;
2418                 case 'H' :
2419                 case 'h' :
2420                         ast_set_flag(&(config->features_caller), AST_FEATURE_DISCONNECT);
2421                         break;
2422                 case 'W' :
2423                 case 'w' :
2424                         ast_set_flag(&(config->features_caller), AST_FEATURE_AUTOMON);
2425                         break;
2426                 default :
2427                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
2428                 }
2429         }
2430 }
2431
2432 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
2433 {
2434         struct ast_datastore *ds_callee_features = NULL, *ds_caller_features = NULL;
2435         struct ast_dial_features *callee_features = NULL, *caller_features = NULL;
2436
2437         ast_channel_lock(caller);
2438         ds_caller_features = ast_channel_datastore_find(caller, &dial_features_info, NULL);
2439         ast_channel_unlock(caller);
2440         if (!ds_caller_features) {
2441                 if (!(ds_caller_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2442                         ast_log(LOG_WARNING, "Unable to create channel datastore for caller features. Aborting!\n");
2443                         return;
2444                 }
2445                 if (!(caller_features = ast_calloc(1, sizeof(*caller_features)))) {
2446                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2447                         ast_datastore_free(ds_caller_features);
2448                         return;
2449                 }
2450                 ds_caller_features->inheritance = DATASTORE_INHERIT_FOREVER;
2451                 caller_features->is_caller = 1;
2452                 ast_copy_flags(&(caller_features->features_callee), &(config->features_callee), AST_FLAGS_ALL);
2453                 ast_copy_flags(&(caller_features->features_caller), &(config->features_caller), AST_FLAGS_ALL);
2454                 ds_caller_features->data = caller_features;
2455                 ast_channel_lock(caller);
2456                 ast_channel_datastore_add(caller, ds_caller_features);
2457                 ast_channel_unlock(caller);
2458         } else {
2459                 /* If we don't return here, then when we do a builtin_atxfer we will copy the disconnect
2460                  * flags over from the atxfer to the caller */
2461                 return;
2462         }
2463
2464         ast_channel_lock(callee);
2465         ds_callee_features = ast_channel_datastore_find(callee, &dial_features_info, NULL);
2466         ast_channel_unlock(callee);
2467         if (!ds_callee_features) {
2468                 if (!(ds_callee_features = ast_datastore_alloc(&dial_features_info, NULL))) {
2469                         ast_log(LOG_WARNING, "Unable to create channel datastore for callee features. Aborting!\n");
2470                         return;
2471                 }
2472                 if (!(callee_features = ast_calloc(1, sizeof(*callee_features)))) {
2473                         ast_log(LOG_WARNING, "Unable to allocate memory for callee feature flags. Aborting!\n");
2474                         ast_datastore_free(ds_callee_features);
2475                         return;
2476                 }
2477                 ds_callee_features->inheritance = DATASTORE_INHERIT_FOREVER;
2478                 callee_features->is_caller = 0;
2479                 ast_copy_flags(&(callee_features->features_callee), &(config->features_caller), AST_FLAGS_ALL);
2480                 ast_copy_flags(&(callee_features->features_caller), &(config->features_callee), AST_FLAGS_ALL);
2481                 ds_callee_features->data = callee_features;
2482                 ast_channel_lock(callee);
2483                 ast_channel_datastore_add(callee, ds_callee_features);
2484                 ast_channel_unlock(callee);
2485         }
2486
2487         return;
2488 }
2489
2490 /*!
2491  * \brief bridge the call and set CDR
2492  * \param chan,peer,config
2493  * 
2494  * Set start time, check for two channels,check if monitor on
2495  * check for feature activation, create new CDR
2496  * \retval res on success.
2497  * \retval -1 on failure to bridge.
2498 */
2499 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
2500 {
2501         /* Copy voice back and forth between the two channels.  Give the peer
2502            the ability to transfer calls with '#<extension' syntax. */
2503         struct ast_frame *f;
2504         struct ast_channel *who;
2505         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
2506         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
2507         char orig_channame[AST_MAX_EXTENSION];
2508         char orig_peername[AST_MAX_EXTENSION];
2509         int res;
2510         int diff;
2511         int hasfeatures=0;
2512         int hadfeatures=0;
2513         int autoloopflag;
2514         struct ast_option_header *aoh;
2515         struct ast_cdr *bridge_cdr = NULL;
2516         struct ast_cdr *orig_peer_cdr = NULL;
2517         struct ast_cdr *chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2518         struct ast_cdr *peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2519         struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2520         struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2521
2522         if (chan && peer) {
2523                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
2524                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
2525         } else if (chan) {
2526                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
2527         }
2528
2529         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
2530         add_features_datastores(chan, peer, config);
2531
2532         /* This is an interesting case.  One example is if a ringing channel gets redirected to
2533          * an extension that picks up a parked call.  This will make sure that the call taken
2534          * out of parking gets told that the channel it just got bridged to is still ringing. */
2535         if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
2536                 ast_indicate(peer, AST_CONTROL_RINGING);
2537         }
2538
2539         if (monitor_ok) {
2540                 const char *monitor_exec;
2541                 struct ast_channel *src = NULL;
2542                 if (!monitor_app) {
2543                         if (!(monitor_app = pbx_findapp("Monitor")))
2544                                 monitor_ok=0;
2545                 }
2546                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
2547                         src = chan;
2548                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
2549                         src = peer;
2550                 if (monitor_app && src) {
2551                         char *tmp = ast_strdupa(monitor_exec);
2552                         pbx_exec(src, monitor_app, tmp);
2553                 }
2554         }
2555
2556         set_config_flags(chan, peer, config);
2557
2558         /* Answer if need be */
2559         if (chan->_state != AST_STATE_UP) {
2560                 if (ast_raw_answer(chan, 1)) {
2561                         return -1;
2562                 }
2563         }
2564
2565         ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
2566         ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
2567         orig_peer_cdr = peer_cdr;
2568         
2569         if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
2570                 
2571                 if (chan_cdr) {
2572                         ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
2573                         ast_cdr_update(chan);
2574                         bridge_cdr = ast_cdr_dup(chan_cdr);
2575                         ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
2576                         ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
2577                 } else {
2578                         /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
2579                         bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
2580                         ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
2581                         ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
2582                         ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
2583                         ast_copy_string(bridge_cdr->lastapp, S_OR(chan->appl, ""), sizeof(bridge_cdr->lastapp));
2584                         ast_copy_string(bridge_cdr->lastdata, S_OR(chan->data, ""), sizeof(bridge_cdr->lastdata));
2585                         ast_cdr_setcid(bridge_cdr, chan);
2586                         bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
2587                         bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
2588                         ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
2589                         /* Destination information */
2590                         ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
2591                         ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
2592                         if (peer_cdr) {
2593                                 bridge_cdr->start = peer_cdr->start;
2594                                 ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
2595                         } else {
2596                                 ast_cdr_start(bridge_cdr);
2597                         }
2598                 }
2599                 ast_debug(4,"bridge answer set, chan answer set\n");
2600                 /* peer_cdr->answer will be set when a macro runs on the peer;
2601                    in that case, the bridge answer will be delayed while the
2602                    macro plays on the peer channel. The peer answered the call
2603                    before the macro started playing. To the phone system,
2604                    this is billable time for the call, even tho the caller
2605                    hears nothing but ringing while the macro does its thing. */
2606                 if (peer_cdr && !ast_tvzero(peer_cdr->answer)) {
2607                         bridge_cdr->answer = peer_cdr->answer;
2608                         chan_cdr->answer = peer_cdr->answer;
2609                         bridge_cdr->disposition = peer_cdr->disposition;
2610                         chan_cdr->disposition = peer_cdr->disposition;
2611                 } else {
2612                         ast_cdr_answer(bridge_cdr);
2613                         ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
2614                 }
2615                 if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2616                         ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
2617                         if (peer_cdr) {
2618                                 ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
2619                         }
2620                 }
2621         }
2622         for (;;) {
2623                 struct ast_channel *other;      /* used later */
2624         
2625                 res = ast_channel_bridge(chan, peer, config, &f, &who);
2626                 
2627                 /* When frame is not set, we are probably involved in a situation
2628                    where we've timed out.
2629                    When frame is set, we'll come this code twice; once for DTMF_BEGIN
2630                    and also for DTMF_END. If we flow into the following 'if' for both, then 
2631                    our wait times are cut in half, as both will subtract from the
2632                    feature_timer. Not good!
2633                 */
2634                 if (config->feature_timer && (!f || f->frametype == AST_FRAME_DTMF_END)) {
2635                         /* Update feature timer for next pass */
2636                         diff = ast_tvdiff_ms(ast_tvnow(), config->feature_start_time);
2637                         if (res == AST_BRIDGE_RETRY) {
2638                                 /* The feature fully timed out but has not been updated. Skip
2639                                  * the potential round error from the diff calculation and
2640                                  * explicitly set to expired. */
2641                                 config->feature_timer = -1;
2642                         } else {
2643                                 config->feature_timer -= diff;
2644                         }
2645
2646                         if (hasfeatures) {
2647                                 if (config->feature_timer <= 0) {
2648                                         /* Not *really* out of time, just out of time for
2649                                            digits to come in for features. */
2650                                         ast_debug(1, "Timed out for feature!\n");
2651                                         if (!ast_strlen_zero(peer_featurecode)) {
2652                                                 ast_dtmf_stream(chan, peer, peer_featurecode, 0, 0);
2653                                                 memset(peer_featurecode, 0, sizeof(peer_featurecode));
2654                                         }
2655                                         if (!ast_strlen_zero(chan_featurecode)) {
2656                                                 ast_dtmf_stream(peer, chan, chan_featurecode, 0, 0);
2657                                                 memset(chan_featurecode, 0, sizeof(chan_featurecode));
2658                                         }
2659                                         if (f)
2660                                                 ast_frfree(f);
2661                                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2662                                         if (!hasfeatures) {
2663                                                 /* No more digits expected - reset the timer */
2664                                                 config->feature_timer = 0;
2665                                         }
2666                                         hadfeatures = hasfeatures;
2667                                         /* Continue as we were */
2668                                         continue;
2669                                 } else if (!f) {
2670                                         /* The bridge returned without a frame and there is a feature in progress.
2671                                          * However, we don't think the feature has quite yet timed out, so just
2672                                          * go back into the bridge. */
2673                                         continue;
2674                                 }
2675                         } else {
2676                                 if (config->feature_timer <=0) {
2677                                         /* We ran out of time */
2678                                         config->feature_timer = 0;
2679                                         who = chan;
2680                                         if (f)
2681                                                 ast_frfree(f);
2682                                         f = NULL;
2683                                         res = 0;
2684                                 }
2685                         }
2686                 }
2687                 if (res < 0) {
2688                         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer)) {
2689                                 ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
2690                         }
2691                         goto before_you_go;
2692                 }
2693                 
2694                 if (!f || (f->frametype == AST_FRAME_CONTROL &&
2695                                 (f->subclass == AST_CONTROL_HANGUP || f->subclass == AST_CONTROL_BUSY ||
2696                                         f->subclass == AST_CONTROL_CONGESTION))) {
2697                         res = -1;
2698                         break;
2699                 }
2700                 /* many things should be sent to the 'other' channel */
2701                 other = (who == chan) ? peer : chan;
2702                 if (f->frametype == AST_FRAME_CONTROL) {
2703                         switch (f->subclass) {
2704                         case AST_CONTROL_RINGING:
2705                         case AST_CONTROL_FLASH:
2706                         case -1:
2707                                 ast_indicate(other, f->subclass);
2708                                 break;
2709                         case AST_CONTROL_HOLD:
2710                         case AST_CONTROL_UNHOLD:
2711                                 ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
2712                                 break;
2713                         case AST_CONTROL_OPTION:
2714                                 aoh = f->data.ptr;
2715                                 /* Forward option Requests */
2716                                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2717                                         ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
2718                                                 f->datalen - sizeof(struct ast_option_header), 0);
2719                                 }
2720                                 break;
2721                         }
2722                 } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
2723                         /* eat it */
2724                 } else if (f->frametype == AST_FRAME_DTMF) {
2725                         char *featurecode;
2726                         int sense;
2727
2728                         hadfeatures = hasfeatures;
2729                         /* This cannot overrun because the longest feature is one shorter than our buffer */
2730                         if (who == chan) {
2731                                 sense = FEATURE_SENSE_CHAN;
2732                                 featurecode = chan_featurecode;
2733                         } else  {
2734                                 sense = FEATURE_SENSE_PEER;
2735                                 featurecode = peer_featurecode;
2736                         }
2737                         /*! append the event to featurecode. we rely on the string being zero-filled, and
2738                          * not overflowing it. 
2739                          * \todo XXX how do we guarantee the latter ?
2740                          */
2741                         featurecode[strlen(featurecode)] = f->subclass;
2742                         /* Get rid of the frame before we start doing "stuff" with the channels */
2743                         ast_frfree(f);
2744                         f = NULL;
2745                         config->feature_timer = 0;
2746                         res = feature_interpret(chan, peer, config, featurecode, sense);
2747                         switch(res) {
2748                         case AST_FEATURE_RETURN_PASSDIGITS:
2749                                 ast_dtmf_stream(other, who, featurecode, 0, 0);
2750                                 /* Fall through */
2751                         case AST_FEATURE_RETURN_SUCCESS:
2752                                 memset(featurecode, 0, sizeof(chan_featurecode));
2753                                 break;
2754                         }
2755                         if (res >= AST_FEATURE_RETURN_PASSDIGITS) {
2756                                 res = 0;
2757                         } else {
2758                                 break;
2759                         }
2760                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2761                         if (hadfeatures && !hasfeatures) {
2762                                 /* Feature completed or timed out */
2763                                 config->feature_timer = 0;
2764                         } else if (hasfeatures) {
2765                                 if (config->timelimit) {
2766                                         /* No warning next time - we are waiting for future */
2767                                         ast_set_flag(config, AST_FEATURE_WARNING_ACTIVE);
2768                                 }
2769                                 config->feature_start_time = ast_tvnow();
2770                                 config->feature_timer = featuredigittimeout;
2771                                 ast_debug(1, "Set feature timer to %ld\n", config->feature_timer);
2772                         }
2773                 }
2774                 if (f)
2775                         ast_frfree(f);
2776
2777         }
2778    before_you_go:
2779
2780         if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2781                 ast_clear_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT); /* its job is done */
2782                 if (bridge_cdr) {
2783                         ast_cdr_discard(bridge_cdr);
2784                         /* QUESTION: should we copy bridge_cdr fields to the peer before we throw it away? */
2785                 }
2786                 return res; /* if we shouldn't do the h-exten, we shouldn't do the bridge cdr, either! */
2787         }
2788
2789         if (config->end_bridge_callback) {
2790                 config->end_bridge_callback(config->end_bridge_callback_data);
2791         }
2792
2793         /* run the hangup exten on the chan object IFF it was NOT involved in a parking situation 
2794          * if it were, then chan belongs to a different thread now, and might have been hung up long
2795      * ago.
2796          */
2797         if (!ast_test_flag(&(config->features_caller),AST_FEATURE_NO_H_EXTEN) &&
2798                 ast_exists_extension(chan, chan->context, "h", 1, chan->cid.cid_num)) {
2799                 struct ast_cdr *swapper = NULL;
2800                 char savelastapp[AST_MAX_EXTENSION];
2801                 char savelastdata[AST_MAX_EXTENSION];
2802                 char save_exten[AST_MAX_EXTENSION];
2803                 int  save_prio;
2804                 int  found = 0; /* set if we find at least one match */
2805                 int  spawn_error = 0;
2806                 
2807                 autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
2808                 ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
2809                 if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
2810                         ast_cdr_end(bridge_cdr);
2811                 }
2812                 /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
2813                    dialplan code operate on it */
2814                 ast_channel_lock(chan);
2815                 if (bridge_cdr) {
2816                         swapper = chan->cdr;
2817                         ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
2818                         ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
2819                         chan->cdr = bridge_cdr;
2820                 }
2821                 ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
2822                 save_prio = chan->priority;
2823                 ast_copy_string(chan->exten, "h", sizeof(chan->exten));
2824                 chan->priority = 1;
2825                 ast_channel_unlock(chan);
2826                 while ((spawn_error = ast_spawn_extension(chan, chan->context, chan->exten, chan->priority, chan->cid.cid_num, &found, 1)) == 0) {
2827                         chan->priority++;
2828                 }
2829                 if (found && spawn_error) {
2830                         /* Something bad happened, or a hangup has been requested. */
2831                         ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2832                         ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2833                 }
2834                 /* swap it back */
2835                 ast_channel_lock(chan);
2836                 ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
2837                 chan->priority = save_prio;
2838                 if (bridge_cdr) {
2839                         if (chan->cdr == bridge_cdr) {
2840                                 chan->cdr = swapper;
2841                         } else {
2842                                 bridge_cdr = NULL;
2843                         }
2844                 }
2845                 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
2846                 ast_channel_unlock(chan);
2847                 /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
2848                 if (bridge_cdr) {
2849                         ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
2850                         ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
2851                 }
2852                 ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
2853         }
2854         
2855         /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
2856         new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2857         if (bridge_cdr && new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED))
2858                 ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
2859
2860         /* we can post the bridge CDR at this point */
2861         if (bridge_cdr) {
2862                 ast_cdr_end(bridge_cdr);
2863                 ast_cdr_detach(bridge_cdr);
2864         }
2865         
2866         /* do a specialized reset on the beginning channel
2867            CDR's, if they still exist, so as not to mess up
2868            issues in future bridges;
2869            
2870            Here are the rules of the game:
2871            1. The chan and peer channel pointers will not change
2872               during the life of the bridge.
2873            2. But, in transfers, the channel names will change.
2874               between the time the bridge is started, and the
2875               time the channel ends. 
2876               Usually, when a channel changes names, it will
2877               also change CDR pointers.
2878            3. Usually, only one of the two channels (chan or peer)
2879               will change names.
2880            4. Usually, if a channel changes names during a bridge,
2881               it is because of a transfer. Usually, in these situations,
2882               it is normal to see 2 bridges running simultaneously, and
2883               it is not unusual to see the two channels that change
2884               swapped between bridges.
2885            5. After a bridge occurs, we have 2 or 3 channels' CDRs
2886               to attend to; if the chan or peer changed names,
2887               we have the before and after attached CDR's.
2888         */
2889
2890         if (new_chan_cdr) {
2891                 struct ast_channel *chan_ptr = NULL;
2892
2893                 if (strcasecmp(orig_channame, chan->name) != 0) { 
2894                         /* old channel */
2895                         if ((chan_ptr = ast_channel_get_by_name(orig_channame))) {
2896                                 ast_channel_lock(chan_ptr);
2897                                 if (!ast_bridged_channel(chan_ptr)) {
2898                                         struct ast_cdr *cur;
2899                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2900                                                 if (cur == chan_cdr) {
2901                                                         break;
2902                                                 }
2903                                         }
2904                                         if (cur) {
2905                                                 ast_cdr_specialized_reset(chan_cdr, 0);
2906                                         }
2907                                 }
2908                                 ast_channel_unlock(chan_ptr);
2909                                 chan_ptr = ast_channel_unref(chan_ptr);
2910                         }
2911                         /* new channel */
2912                         ast_cdr_specialized_reset(new_chan_cdr, 0);
2913                 } else {
2914                         ast_cdr_specialized_reset(chan_cdr, 0); /* nothing changed, reset the chan_cdr  */
2915                 }
2916         }
2917
2918         {
2919                 struct ast_channel *chan_ptr = NULL;
2920                 new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2921                 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))
2922                         ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
2923                 if (strcasecmp(orig_peername, peer->name) != 0) { 
2924                         /* old channel */
2925                         if ((chan_ptr = ast_channel_get_by_name(orig_peername))) {
2926                                 ast_channel_lock(chan_ptr);
2927                                 if (!ast_bridged_channel(chan_ptr)) {
2928                                         struct ast_cdr *cur;
2929                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2930                                                 if (cur == peer_cdr) {
2931                                                         break;
2932                                                 }
2933                                         }
2934                                         if (cur) {
2935                                                 ast_cdr_specialized_reset(peer_cdr, 0);
2936                                         }
2937                                 }
2938                                 ast_channel_unlock(chan_ptr);
2939                                 chan_ptr = ast_channel_unref(chan_ptr);
2940                         }
2941                         /* new channel */
2942                         ast_cdr_specialized_reset(new_peer_cdr, 0);
2943                 } else {
2944                         ast_cdr_specialized_reset(peer_cdr, 0); /* nothing changed, reset the peer_cdr  */
2945                 }
2946         }
2947         
2948         return res;
2949 }
2950
2951 /*! \brief Output parking event to manager */
2952 static void post_manager_event(const char *s, struct parkeduser *pu)
2953 {
2954         manager_event(EVENT_FLAG_CALL, s,
2955                 "Exten: %s\r\n"
2956                 "Channel: %s\r\n"
2957                 "Parkinglot: %s\r\n"
2958                 "CallerIDNum: %s\r\n"
2959                 "CallerIDName: %s\r\n"
2960                 "UniqueID: %s\r\n\r\n",
2961                 pu->parkingexten, 
2962                 pu->chan->name,
2963                 pu->parkinglot->name,
2964                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
2965                 S_OR(pu->chan->cid.cid_name, "<unknown>"),
2966                 pu->chan->uniqueid
2967                 );
2968 }
2969
2970 static char *callback_dialoptions(struct ast_flags *features_callee, struct ast_flags *features_caller, char *options, size_t len)
2971 {
2972         int i = 0;
2973         enum {
2974                 OPT_CALLEE_REDIRECT   = 't',
2975                 OPT_CALLER_REDIRECT   = 'T',
2976                 OPT_CALLEE_AUTOMON    = 'w',
2977                 OPT_CALLER_AUTOMON    = 'W',
2978                 OPT_CALLEE_DISCONNECT = 'h',
2979                 OPT_CALLER_DISCONNECT = 'H',
2980                 OPT_CALLEE_PARKCALL   = 'k',
2981                 OPT_CALLER_PARKCALL   = 'K',
2982         };
2983
2984         memset(options, 0, len);
2985         if (ast_test_flag(features_caller, AST_FEATURE_REDIRECT) && i < len) {
2986                 options[i++] = OPT_CALLER_REDIRECT;
2987         }
2988         if (ast_test_flag(features_caller, AST_FEATURE_AUTOMON) && i < len) {
2989                 options[i++] = OPT_CALLER_AUTOMON;
2990         }
2991         if (ast_test_flag(features_caller, AST_FEATURE_DISCONNECT) && i < len) {
2992                 options[i++] = OPT_CALLER_DISCONNECT;
2993         }
2994         if (ast_test_flag(features_caller, AST_FEATURE_PARKCALL) && i < len) {
2995                 options[i++] = OPT_CALLER_PARKCALL;
2996         }
2997
2998         if (ast_test_flag(features_callee, AST_FEATURE_REDIRECT) && i < len) {
2999                 options[i++] = OPT_CALLEE_REDIRECT;
3000         }
3001         if (ast_test_flag(features_callee, AST_FEATURE_AUTOMON) && i < len) {
3002                 options[i++] = OPT_CALLEE_AUTOMON;
3003         }
3004         if (ast_test_flag(features_callee, AST_FEATURE_DISCONNECT) && i < len) {
3005                 options[i++] = OPT_CALLEE_DISCONNECT;
3006         }
3007         if (ast_test_flag(features_callee, AST_FEATURE_PARKCALL) && i < len) {
3008                 options[i++] = OPT_CALLEE_PARKCALL;
3009         }
3010
3011         return options;
3012 }
3013
3014 /*! \brief Run management on parkinglots, called once per parkinglot */
3015 int manage_parkinglot(struct ast_parkinglot *curlot, fd_set *rfds, fd_set *efds, fd_set *nrfds, fd_set *nefds, int *ms, int *max)
3016 {
3017
3018         struct parkeduser *pu;
3019         int res = 0;
3020         char parkingslot[AST_MAX_EXTENSION];
3021
3022         /* Lock parking list */
3023         AST_LIST_LOCK(&curlot->parkings);
3024         AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
3025                 struct ast_channel *chan = pu->chan;    /* shorthand */
3026                 int tms;        /* timeout for this item */
3027                 int x;          /* fd index in channel */
3028                 struct ast_context *con;
3029
3030                 if (pu->notquiteyet) { /* Pretend this one isn't here yet */