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