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