Merged revisions 172030 via svnmerge from
[asterisk/asterisk.git] / main / features.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Routines implementing call features as call pickup, parking and transfer
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31
32 #include <pthread.h>
33 #include <sys/time.h>
34 #include <sys/signal.h>
35 #include <netinet/in.h>
36
37 #include "asterisk/lock.h"
38 #include "asterisk/file.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/causes.h"
42 #include "asterisk/module.h"
43 #include "asterisk/translate.h"
44 #include "asterisk/app.h"
45 #include "asterisk/say.h"
46 #include "asterisk/features.h"
47 #include "asterisk/musiconhold.h"
48 #include "asterisk/config.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/manager.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/adsi.h"
53 #include "asterisk/devicestate.h"
54 #include "asterisk/monitor.h"
55 #include "asterisk/audiohook.h"
56 #include "asterisk/global_datastores.h"
57 #include "asterisk/astobj2.h"
58
59 /*** DOCUMENTATION
60         <application name="Bridge" language="en_US">
61                 <synopsis>
62                         Bridge two channels.
63                 </synopsis>
64                 <syntax>
65                         <parameter name="channel" required="true">
66                                 <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
67                         </parameter>
68                         <parameter name="options">
69                                 <optionlist>
70                                         <option name="p">
71                                                 <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
72                                         </option>
73                                 </optionlist>
74                         </parameter>
75                 </syntax>
76                 <description>
77                         <para>Allows the ability to bridge two channels via the dialplan.</para>
78                         <para>This application sets the following channel variable upon completion:</para>
79                         <variablelist>
80                                 <variable name="BRIDGERESULT">
81                                         <para>The result of the bridge attempt as a text string.</para>
82                                         <value name="SUCCESS" />
83                                         <value name="FAILURE" />
84                                         <value name="LOOP" />
85                                         <value name="NONEXISTENT" />
86                                         <value name="INCOMPATIBLE" />
87                                 </variable>
88                         </variablelist>
89                 </description>
90         </application>
91         <application name="ParkedCall" language="en_US">
92                 <synopsis>
93                         Answer a parked call.
94                 </synopsis>
95                 <syntax>
96                         <parameter name="exten" required="true" />
97                 </syntax>
98                 <description>
99                         <para>Used to connect to a parked call. This application is always
100                         registered internally and does not need to be explicitly added
101                         into the dialplan, although you should include the <literal>parkedcalls</literal>
102                         context. If no extension is provided, then the first available
103                         parked call will be acquired.</para>
104                 </description>
105                 <see-also>
106                         <ref type="application">Park</ref>
107                         <ref type="application">ParkAndAnnounce</ref>
108                 </see-also>
109         </application>
110         <application name="Park" language="en_US">
111                 <synopsis>
112                         Park yourself.
113                 </synopsis>
114                 <syntax>
115                         <parameter name="timeout">
116                                 <para>A custom parking timeout for this parked call.</para>
117                         </parameter>
118                         <parameter name="return_context">
119                                 <para>The context to return the call to after it times out.</para>
120                         </parameter>
121                         <parameter name="return_exten">
122                                 <para>The extension to return the call to after it times out.</para>
123                         </parameter>
124                         <parameter name="return_priority">
125                                 <para>The priority to return the call to after it times out.</para>
126                         </parameter>
127                         <parameter name="options">
128                                 <para>A list of options for this parked call.</para>
129                                 <optionlist>
130                                         <option name="r">
131                                                 <para>Send ringing instead of MOH to the parked call.</para>
132                                         </option>
133                                         <option name="R">
134                                                 <para>Randomize the selection of a parking space.</para>
135                                         </option>
136                                         <option name="s">
137                                                 <para>Silence announcement of the parking space number.</para>
138                                         </option>
139                                 </optionlist>
140                         </parameter>
141                 </syntax>
142                 <description>
143                         <para>Used to park yourself (typically in combination with a supervised
144                         transfer to know the parking space). This application is always
145                         registered internally and does not need to be explicitly added
146                         into the dialplan, although you should include the <literal>parkedcalls</literal>
147                         context (or the context specified in <filename>features.conf</filename>).</para>
148                         <para>If you set the <variable>PARKINGEXTEN</variable> variable to an extension in your
149                         parking context, Park() will park the call on that extension, unless
150                         it already exists. In that case, execution will continue at next priority.</para>
151                 </description>
152                 <see-also>
153                         <ref type="application">ParkAndAnnounce</ref>
154                         <ref type="application">ParkedCall</ref>
155                 </see-also>
156         </application>
157  ***/
158
159 #define DEFAULT_PARK_TIME 45000
160 #define DEFAULT_TRANSFER_DIGIT_TIMEOUT 3000
161 #define DEFAULT_FEATURE_DIGIT_TIMEOUT 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) { /* this code should never get called (in a perfect world) */
1231                         transferer->cdr=ast_cdr_alloc();
1232                         if (transferer->cdr) {
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                         struct ast_cdr *swap = transferer->cdr;
1239                         ast_log(LOG_DEBUG,"transferer=%s; transferee=%s; lastapp=%s; lastdata=%s; chan=%s; dstchan=%s\n",
1240                                         transferer->name, transferee->name, transferer->cdr->lastapp, transferer->cdr->lastdata, 
1241                                         transferer->cdr->channel, transferer->cdr->dstchannel);
1242                         ast_log(LOG_DEBUG,"TRANSFEREE; lastapp=%s; lastdata=%s, chan=%s; dstchan=%s\n",
1243                                         transferee->cdr->lastapp, transferee->cdr->lastdata, transferee->cdr->channel, transferee->cdr->dstchannel);
1244                         ast_log(LOG_DEBUG,"transferer_real_context=%s; xferto=%s\n", transferer_real_context, xferto);
1245                         /* swap cdrs-- it will save us some time & work */
1246                         transferer->cdr = transferee->cdr;
1247                         transferee->cdr = swap;
1248                 }
1249                 if (!transferee->pbx) {
1250                         /* Doh!  Use our handy async_goto functions */
1251                         ast_verb(3, "Transferring %s to '%s' (context %s) priority 1\n"
1252                                                                 ,transferee->name, xferto, transferer_real_context);
1253                         if (ast_async_goto(transferee, transferer_real_context, xferto, 1))
1254                                 ast_log(LOG_WARNING, "Async goto failed :-(\n");
1255                 } else {
1256                         /* Set the channel's new extension, since it exists, using transferer context */
1257                         ast_set_flag(transferee, AST_FLAG_BRIDGE_HANGUP_DONT); /* don't let the after-bridge code run the h-exten */
1258                         ast_log(LOG_DEBUG,"ABOUT TO AST_ASYNC_GOTO, have a pbx... set HANGUP_DONT on chan=%s\n", transferee->name);
1259                         set_c_e_p(transferee, transferer_real_context, xferto, 0);
1260                 }
1261                 check_goto_on_transfer(transferer);
1262                 return res;
1263         } else {
1264                 ast_verb(3, "Unable to find extension '%s' in context '%s'\n", xferto, transferer_real_context);
1265         }
1266         if (ast_stream_and_wait(transferer, xferfailsound, AST_DIGIT_ANY) < 0) {
1267                 finishup(transferee);
1268                 return -1;
1269         }
1270         ast_stopstream(transferer);
1271         res = finishup(transferee);
1272         if (res) {
1273                 ast_verb(2, "Hungup during autoservice stop on '%s'\n", transferee->name);
1274                 return res;
1275         }
1276         return AST_FEATURE_RETURN_SUCCESS;
1277 }
1278
1279 /*!
1280  * \brief make channels compatible
1281  * \param c
1282  * \param newchan
1283  * \retval 0 on success.
1284  * \retval -1 on failure.
1285 */
1286 static int check_compat(struct ast_channel *c, struct ast_channel *newchan)
1287 {
1288         if (ast_channel_make_compatible(c, newchan) < 0) {
1289                 ast_log(LOG_WARNING, "Had to drop call because I couldn't make %s compatible with %s\n",
1290                         c->name, newchan->name);
1291                 ast_hangup(newchan);
1292                 return -1;
1293         }
1294         return 0;
1295 }
1296
1297 /*!
1298  * \brief Attended transfer
1299  * \param chan transfered user
1300  * \param peer person transfering call
1301  * \param config
1302  * \param code
1303  * \param sense feature options
1304  * 
1305  * \param data
1306  * Get extension to transfer to, if you cannot generate channel (or find extension) 
1307  * return to host channel. After called channel answered wait for hangup of transferer,
1308  * bridge call between transfer peer (taking them off hold) to attended transfer channel.
1309  *
1310  * \return -1 on failure
1311 */
1312 static int builtin_atxfer(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1313 {
1314         struct ast_channel *transferer;
1315         struct ast_channel *transferee;
1316         const char *transferer_real_context;
1317         char xferto[256] = "";
1318         int res;
1319         int outstate=0;
1320         struct ast_channel *newchan;
1321         struct ast_channel *xferchan;
1322         struct ast_bridge_thread_obj *tobj;
1323         struct ast_bridge_config bconfig;
1324         struct ast_frame *f;
1325         int l;
1326
1327         ast_debug(1, "Executing Attended Transfer %s, %s (sense=%d) \n", chan->name, peer->name, sense);
1328         set_peers(&transferer, &transferee, peer, chan, sense);
1329         transferer_real_context = real_ctx(transferer, transferee);
1330         /* Start autoservice on chan while we talk to the originator */
1331         ast_autoservice_start(transferee);
1332         ast_indicate(transferee, AST_CONTROL_HOLD);
1333         
1334         /* Transfer */
1335         res = ast_stream_and_wait(transferer, "pbx-transfer", AST_DIGIT_ANY);
1336         if (res < 0) {
1337                 finishup(transferee);
1338                 return res;
1339         }
1340         if (res > 0) /* If they've typed a digit already, handle it */
1341                 xferto[0] = (char) res;
1342
1343         /* this is specific of atxfer */
1344         res = ast_app_dtget(transferer, transferer_real_context, xferto, sizeof(xferto), 100, transferdigittimeout);
1345         if (res < 0) {  /* hangup, would be 0 for invalid and 1 for valid */
1346                 finishup(transferee);
1347                 return res;
1348         }
1349         if (res == 0) {
1350                 ast_log(LOG_WARNING, "Did not read data.\n");
1351                 finishup(transferee);
1352                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1353                         return -1;
1354                 return AST_FEATURE_RETURN_SUCCESS;
1355         }
1356
1357         /* valid extension, res == 1 */
1358         if (!ast_exists_extension(transferer, transferer_real_context, xferto, 1, transferer->cid.cid_num)) {
1359                 ast_log(LOG_WARNING, "Extension %s does not exist in context %s\n",xferto,transferer_real_context);
1360                 finishup(transferee);
1361                 if (ast_stream_and_wait(transferer, "beeperr", ""))
1362                         return -1;
1363                 return AST_FEATURE_RETURN_SUCCESS;
1364         }
1365
1366         l = strlen(xferto);
1367         snprintf(xferto + l, sizeof(xferto) - l, "@%s/n", transferer_real_context);     /* append context */
1368
1369         /* If we are performing an attended transfer and we have two channels involved then
1370            copy sound file information to play upon attended transfer completion */
1371         if (transferee) {
1372                 const char *chan1_attended_sound = pbx_builtin_getvar_helper(transferer, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1373                 const char *chan2_attended_sound = pbx_builtin_getvar_helper(transferee, "ATTENDED_TRANSFER_COMPLETE_SOUND");
1374
1375                 if (!ast_strlen_zero(chan1_attended_sound)) {
1376                         pbx_builtin_setvar_helper(transferer, "BRIDGE_PLAY_SOUND", chan1_attended_sound);
1377                 }
1378                 if (!ast_strlen_zero(chan2_attended_sound)) {
1379                         pbx_builtin_setvar_helper(transferee, "BRIDGE_PLAY_SOUND", chan2_attended_sound);
1380                 }
1381         }
1382
1383         newchan = ast_feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
1384                 xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
1385
1386         if (!ast_check_hangup(transferer)) {
1387                 /* Transferer is up - old behaviour */
1388                 ast_indicate(transferer, -1);
1389                 if (!newchan) {
1390                         finishup(transferee);
1391                         /* any reason besides user requested cancel and busy triggers the failed sound */
1392                         if (outstate != AST_CONTROL_UNHOLD && outstate != AST_CONTROL_BUSY &&
1393                                 ast_stream_and_wait(transferer, xferfailsound, ""))
1394                                 return -1;
1395                         if (ast_stream_and_wait(transferer, xfersound, ""))
1396                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1397                         return AST_FEATURE_RETURN_SUCCESS;
1398                 }
1399
1400                 if (check_compat(transferer, newchan)) {
1401                         /* we do mean transferee here, NOT transferer */
1402                         finishup(transferee);
1403                         return -1;
1404                 }
1405                 memset(&bconfig,0,sizeof(struct ast_bridge_config));
1406                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1407                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1408                 res = ast_bridge_call(transferer, newchan, &bconfig);
1409                 if (ast_check_hangup(newchan) || !ast_check_hangup(transferer)) {
1410                         ast_hangup(newchan);
1411                         if (ast_stream_and_wait(transferer, xfersound, ""))
1412                                 ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1413                         finishup(transferee);
1414                         transferer->_softhangup = 0;
1415                         return AST_FEATURE_RETURN_SUCCESS;
1416                 }
1417                 if (check_compat(transferee, newchan)) {
1418                         finishup(transferee);
1419                         return -1;
1420                 }
1421                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
1422
1423                 if ((ast_autoservice_stop(transferee) < 0)
1424                  || (ast_waitfordigit(transferee, 100) < 0)
1425                  || (ast_waitfordigit(newchan, 100) < 0)
1426                  || ast_check_hangup(transferee)
1427                  || ast_check_hangup(newchan)) {
1428                         ast_hangup(newchan);
1429                         return -1;
1430                 }
1431                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Transfered/%s", transferee->name);
1432                 if (!xferchan) {
1433                         ast_hangup(newchan);
1434                         return -1;
1435                 }
1436                 /* Make formats okay */
1437                 xferchan->visible_indication = transferer->visible_indication;
1438                 xferchan->readformat = transferee->readformat;
1439                 xferchan->writeformat = transferee->writeformat;
1440                 ast_channel_masquerade(xferchan, transferee);
1441                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
1442                 xferchan->_state = AST_STATE_UP;
1443                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
1444                 xferchan->_softhangup = 0;
1445                 if ((f = ast_read(xferchan)))
1446                         ast_frfree(f);
1447                 newchan->_state = AST_STATE_UP;
1448                 ast_clear_flag(newchan, AST_FLAGS_ALL);
1449                 newchan->_softhangup = 0;
1450                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
1451                         ast_hangup(xferchan);
1452                         ast_hangup(newchan);
1453                         return -1;
1454                 }
1455                 tobj->chan = newchan;
1456                 tobj->peer = xferchan;
1457                 tobj->bconfig = *config;
1458
1459                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
1460                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
1461                 }
1462
1463                 if (ast_stream_and_wait(newchan, xfersound, ""))
1464                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1465                 ast_bridge_call_thread_launch(tobj);
1466                 return -1;      /* XXX meaning the channel is bridged ? */
1467         } else if (!ast_check_hangup(transferee)) {
1468                 /* act as blind transfer */
1469                 if (ast_autoservice_stop(transferee) < 0) {
1470                         ast_hangup(newchan);
1471                         return -1;
1472                 }
1473
1474                 if (!newchan) {
1475                         unsigned int tries = 0;
1476                         char *transferer_tech, *transferer_name = ast_strdupa(transferer->name);
1477
1478                         transferer_tech = strsep(&transferer_name, "/");
1479                         transferer_name = strsep(&transferer_name, "-");
1480
1481                         if (ast_strlen_zero(transferer_name) || ast_strlen_zero(transferer_tech)) {
1482                                 ast_log(LOG_WARNING, "Transferer has invalid channel name: '%s'\n", transferer->name);
1483                                 if (ast_stream_and_wait(transferee, "beeperr", ""))
1484                                         return -1;
1485                                 return AST_FEATURE_RETURN_SUCCESS;
1486                         }
1487
1488                         ast_log(LOG_NOTICE, "We're trying to call %s/%s\n", transferer_tech, transferer_name);
1489                         newchan = ast_feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
1490                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
1491                         while (!newchan && !atxferdropcall && tries < atxfercallbackretries) {
1492                                 /* Trying to transfer again */
1493                                 ast_autoservice_start(transferee);
1494                                 ast_indicate(transferee, AST_CONTROL_HOLD);
1495
1496                                 newchan = ast_feature_request_and_dial(transferer, transferee, "Local", ast_best_codec(transferer->nativeformats),
1497                                         xferto, atxfernoanswertimeout, &outstate, transferer->cid.cid_num, transferer->cid.cid_name, 1, transferer->language);
1498                                 if (ast_autoservice_stop(transferee) < 0) {
1499                                         if (newchan)
1500                                                 ast_hangup(newchan);
1501                                         return -1;
1502                                 }
1503                                 if (!newchan) {
1504                                         /* Transfer failed, sleeping */
1505                                         ast_debug(1, "Sleeping for %d ms before callback.\n", atxferloopdelay);
1506                                         ast_safe_sleep(transferee, atxferloopdelay);
1507                                         ast_debug(1, "Trying to callback...\n");
1508                                         newchan = ast_feature_request_and_dial(transferee, NULL, transferer_tech, ast_best_codec(transferee->nativeformats),
1509                                                 transferer_name, atxfernoanswertimeout, &outstate, transferee->cid.cid_num, transferee->cid.cid_name, 0, transferer->language);
1510                                 }
1511                                 tries++;
1512                         }
1513                 }
1514                 if (!newchan)
1515                         return -1;
1516
1517                 /* newchan is up, we should prepare transferee and bridge them */
1518                 if (check_compat(transferee, newchan)) {
1519                         finishup(transferee);
1520                         return -1;
1521                 }
1522                 ast_indicate(transferee, AST_CONTROL_UNHOLD);
1523
1524                 if ((ast_waitfordigit(transferee, 100) < 0)
1525                    || (ast_waitfordigit(newchan, 100) < 0)
1526                    || ast_check_hangup(transferee)
1527                    || ast_check_hangup(newchan)) {
1528                         ast_hangup(newchan);
1529                         return -1;
1530                 }
1531
1532                 xferchan = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Transfered/%s", transferee->name);
1533                 if (!xferchan) {
1534                         ast_hangup(newchan);
1535                         return -1;
1536                 }
1537                 /* Make formats okay */
1538                 xferchan->visible_indication = transferer->visible_indication;
1539                 xferchan->readformat = transferee->readformat;
1540                 xferchan->writeformat = transferee->writeformat;
1541                 ast_channel_masquerade(xferchan, transferee);
1542                 ast_explicit_goto(xferchan, transferee->context, transferee->exten, transferee->priority);
1543                 xferchan->_state = AST_STATE_UP;
1544                 ast_clear_flag(xferchan, AST_FLAGS_ALL);
1545                 xferchan->_softhangup = 0;
1546                 if ((f = ast_read(xferchan)))
1547                         ast_frfree(f);
1548                 newchan->_state = AST_STATE_UP;
1549                 ast_clear_flag(newchan, AST_FLAGS_ALL);
1550                 newchan->_softhangup = 0;
1551                 if (!(tobj = ast_calloc(1, sizeof(*tobj)))) {
1552                         ast_hangup(xferchan);
1553                         ast_hangup(newchan);
1554                         return -1;
1555                 }
1556                 tobj->chan = newchan;
1557                 tobj->peer = xferchan;
1558                 tobj->bconfig = *config;
1559
1560                 if (tobj->bconfig.end_bridge_callback_data_fixup) {
1561                         tobj->bconfig.end_bridge_callback_data_fixup(&tobj->bconfig, tobj->peer, tobj->chan);
1562                 }
1563
1564                 if (ast_stream_and_wait(newchan, xfersound, ""))
1565                         ast_log(LOG_WARNING, "Failed to play transfer sound!\n");
1566                 ast_bridge_call_thread_launch(tobj);
1567                 return -1;      /* XXX meaning the channel is bridged ? */
1568         } else {
1569                 /* Transferee hung up */
1570                 finishup(transferee);
1571                 return -1;
1572         }
1573 }
1574
1575 /* add atxfer and automon as undefined so you can only use em if you configure them */
1576 #define FEATURES_COUNT ARRAY_LEN(builtin_features)
1577
1578 AST_RWLOCK_DEFINE_STATIC(features_lock);
1579
1580 static struct ast_call_feature builtin_features[] = 
1581 {
1582         { AST_FEATURE_REDIRECT, "Blind Transfer", "blindxfer", "#", "#", builtin_blindtransfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1583         { AST_FEATURE_REDIRECT, "Attended Transfer", "atxfer", "", "", builtin_atxfer, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1584         { AST_FEATURE_AUTOMON, "One Touch Monitor", "automon", "", "", builtin_automonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1585         { AST_FEATURE_DISCONNECT, "Disconnect Call", "disconnect", "*", "*", builtin_disconnect, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1586         { AST_FEATURE_PARKCALL, "Park Call", "parkcall", "", "", builtin_parkcall, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1587         { AST_FEATURE_AUTOMIXMON, "One Touch MixMonitor", "automixmon", "", "", builtin_automixmonitor, AST_FEATURE_FLAG_NEEDSDTMF, "" },
1588 };
1589
1590
1591 static AST_RWLIST_HEAD_STATIC(feature_list, ast_call_feature);
1592
1593 /*! \brief register new feature into feature_list*/
1594 void ast_register_feature(struct ast_call_feature *feature)
1595 {
1596         if (!feature) {
1597                 ast_log(LOG_NOTICE,"You didn't pass a feature!\n");
1598                 return;
1599         }
1600   
1601         AST_RWLIST_WRLOCK(&feature_list);
1602         AST_RWLIST_INSERT_HEAD(&feature_list,feature,feature_entry);
1603         AST_RWLIST_UNLOCK(&feature_list);
1604
1605         ast_verb(2, "Registered Feature '%s'\n",feature->sname);
1606 }
1607
1608 /*! 
1609  * \brief Add new feature group
1610  * \param fgname feature group name.
1611  *
1612  * Add new feature group to the feature group list insert at head of list.
1613  * \note This function MUST be called while feature_groups is locked.
1614 */
1615 static struct feature_group* register_group(const char *fgname)
1616 {
1617         struct feature_group *fg;
1618
1619         if (!fgname) {
1620                 ast_log(LOG_NOTICE, "You didn't pass a new group name!\n");
1621                 return NULL;
1622         }
1623
1624         if (!(fg = ast_calloc(1, sizeof(*fg))))
1625                 return NULL;
1626
1627         if (ast_string_field_init(fg, 128)) {
1628                 ast_free(fg);
1629                 return NULL;
1630         }
1631
1632         ast_string_field_set(fg, gname, fgname);
1633
1634         AST_LIST_INSERT_HEAD(&feature_groups, fg, entry);
1635
1636         ast_verb(2, "Registered group '%s'\n", fg->gname);
1637
1638         return fg;
1639 }
1640
1641 /*! 
1642  * \brief Add feature to group
1643  * \param fg feature group
1644  * \param exten
1645  * \param feature feature to add.
1646  *
1647  * Check fg and feature specified, add feature to list
1648  * \note This function MUST be called while feature_groups is locked. 
1649 */
1650 static void register_group_feature(struct feature_group *fg, const char *exten, struct ast_call_feature *feature) 
1651 {
1652         struct feature_group_exten *fge;
1653
1654         if (!fg) {
1655                 ast_log(LOG_NOTICE, "You didn't pass a group!\n");
1656                 return;
1657         }
1658
1659         if (!feature) {
1660                 ast_log(LOG_NOTICE, "You didn't pass a feature!\n");
1661                 return;
1662         }
1663
1664         if (!(fge = ast_calloc(1, sizeof(*fge))))
1665                 return;
1666
1667         if (ast_string_field_init(fge, 128)) {
1668                 ast_free(fge);
1669                 return;
1670         }
1671
1672         ast_string_field_set(fge, exten, S_OR(exten, feature->exten));
1673
1674         fge->feature = feature;
1675
1676         AST_LIST_INSERT_HEAD(&fg->features, fge, entry);                
1677
1678         ast_verb(2, "Registered feature '%s' for group '%s' at exten '%s'\n",
1679                                         feature->sname, fg->gname, exten);
1680 }
1681
1682 void ast_unregister_feature(struct ast_call_feature *feature)
1683 {
1684         if (!feature) {
1685                 return;
1686         }
1687
1688         AST_RWLIST_WRLOCK(&feature_list);
1689         AST_RWLIST_REMOVE(&feature_list, feature, feature_entry);
1690         AST_RWLIST_UNLOCK(&feature_list);
1691
1692         ast_free(feature);
1693 }
1694
1695 /*! \brief Remove all features in the list */
1696 static void ast_unregister_features(void)
1697 {
1698         struct ast_call_feature *feature;
1699
1700         AST_RWLIST_WRLOCK(&feature_list);
1701         while ((feature = AST_RWLIST_REMOVE_HEAD(&feature_list, feature_entry))) {
1702                 ast_free(feature);
1703         }
1704         AST_RWLIST_UNLOCK(&feature_list);
1705 }
1706
1707 /*! \brief find a call feature by name */
1708 static struct ast_call_feature *find_dynamic_feature(const char *name)
1709 {
1710         struct ast_call_feature *tmp;
1711
1712         AST_RWLIST_TRAVERSE(&feature_list, tmp, feature_entry) {
1713                 if (!strcasecmp(tmp->sname, name)) {
1714                         break;
1715                 }
1716         }
1717
1718         return tmp;
1719 }
1720
1721 /*! \brief Remove all feature groups in the list */
1722 static void ast_unregister_groups(void)
1723 {
1724         struct feature_group *fg;
1725         struct feature_group_exten *fge;
1726
1727         AST_RWLIST_WRLOCK(&feature_groups);
1728         while ((fg = AST_LIST_REMOVE_HEAD(&feature_groups, entry))) {
1729                 while ((fge = AST_LIST_REMOVE_HEAD(&fg->features, entry))) {
1730                         ast_string_field_free_memory(fge);
1731                         ast_free(fge);
1732                 }
1733
1734                 ast_string_field_free_memory(fg);
1735                 ast_free(fg);
1736         }
1737         AST_RWLIST_UNLOCK(&feature_groups);
1738 }
1739
1740 /*! 
1741  * \brief Find a group by name 
1742  * \param name feature name
1743  * \retval feature group on success.
1744  * \retval NULL on failure.
1745 */
1746 static struct feature_group *find_group(const char *name) {
1747         struct feature_group *fg = NULL;
1748
1749         AST_LIST_TRAVERSE(&feature_groups, fg, entry) {
1750                 if (!strcasecmp(fg->gname, name))
1751                         break;
1752         }
1753
1754         return fg;
1755 }
1756
1757 void ast_rdlock_call_features(void)
1758 {
1759         ast_rwlock_rdlock(&features_lock);
1760 }
1761
1762 void ast_unlock_call_features(void)
1763 {
1764         ast_rwlock_unlock(&features_lock);
1765 }
1766
1767 struct ast_call_feature *ast_find_call_feature(const char *name)
1768 {
1769         int x;
1770         for (x = 0; x < FEATURES_COUNT; x++) {
1771                 if (!strcasecmp(name, builtin_features[x].sname))
1772                         return &builtin_features[x];
1773         }
1774         return NULL;
1775 }
1776
1777 /*!
1778  * \brief exec an app by feature 
1779  * \param chan,peer,config,code,sense,data
1780  *
1781  * Find a feature, determine which channel activated
1782  * \retval AST_FEATURE_RETURN_NO_HANGUP_PEER
1783  * \retval -1 error.
1784  * \retval -2 when an application cannot be found.
1785 */
1786 static int feature_exec_app(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense, void *data)
1787 {
1788         struct ast_app *app;
1789         struct ast_call_feature *feature = data;
1790         struct ast_channel *work, *idle;
1791         int res;
1792
1793         if (!feature) { /* shouldn't ever happen! */
1794                 ast_log(LOG_NOTICE, "Found feature before, but at execing we've lost it??\n");
1795                 return -1; 
1796         }
1797
1798         if (sense == FEATURE_SENSE_CHAN) {
1799                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
1800                         return AST_FEATURE_RETURN_KEEPTRYING;
1801                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
1802                         work = chan;
1803                         idle = peer;
1804                 } else {
1805                         work = peer;
1806                         idle = chan;
1807                 }
1808         } else {
1809                 if (!ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
1810                         return AST_FEATURE_RETURN_KEEPTRYING;
1811                 if (ast_test_flag(feature, AST_FEATURE_FLAG_ONSELF)) {
1812                         work = peer;
1813                         idle = chan;
1814                 } else {
1815                         work = chan;
1816                         idle = peer;
1817                 }
1818         }
1819
1820         if (!(app = pbx_findapp(feature->app))) {
1821                 ast_log(LOG_WARNING, "Could not find application (%s)\n", feature->app);
1822                 return -2;
1823         }
1824
1825         ast_autoservice_start(idle);
1826         
1827         if (!ast_strlen_zero(feature->moh_class))
1828                 ast_moh_start(idle, feature->moh_class, NULL);
1829
1830         res = pbx_exec(work, app, feature->app_args);
1831
1832         if (!ast_strlen_zero(feature->moh_class))
1833                 ast_moh_stop(idle);
1834
1835         ast_autoservice_stop(idle);
1836
1837         if (res) {
1838                 return AST_FEATURE_RETURN_SUCCESSBREAK;
1839         }
1840         return AST_FEATURE_RETURN_SUCCESS;      /*! \todo XXX should probably return res */
1841 }
1842
1843 static void unmap_features(void)
1844 {
1845         int x;
1846
1847         ast_rwlock_wrlock(&features_lock);
1848         for (x = 0; x < FEATURES_COUNT; x++)
1849                 strcpy(builtin_features[x].exten, builtin_features[x].default_exten);
1850         ast_rwlock_unlock(&features_lock);
1851 }
1852
1853 static int remap_feature(const char *name, const char *value)
1854 {
1855         int x, res = -1;
1856
1857         ast_rwlock_wrlock(&features_lock);
1858         for (x = 0; x < FEATURES_COUNT; x++) {
1859                 if (strcasecmp(builtin_features[x].sname, name))
1860                         continue;
1861
1862                 ast_copy_string(builtin_features[x].exten, value, sizeof(builtin_features[x].exten));
1863                 res = 0;
1864                 break;
1865         }
1866         ast_rwlock_unlock(&features_lock);
1867
1868         return res;
1869 }
1870
1871 /*!
1872  * \brief Check the dynamic features
1873  * \param chan,peer,config,code,sense
1874  *
1875  * Lock features list, browse for code, unlock list
1876  * \retval res on success.
1877  * \retval -1 on failure.
1878 */
1879 static int ast_feature_interpret(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, char *code, int sense)
1880 {
1881         int x;
1882         struct ast_flags features;
1883         struct ast_call_feature *feature;
1884         struct feature_group *fg = NULL;
1885         struct feature_group_exten *fge;
1886         const char *dynamic_features;
1887         char *tmp, *tok;
1888         int res = AST_FEATURE_RETURN_PASSDIGITS;
1889         int feature_detected = 0;
1890
1891         if (sense == FEATURE_SENSE_CHAN) {
1892                 ast_copy_flags(&features, &(config->features_caller), AST_FLAGS_ALL);
1893                 dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
1894         }
1895         else {
1896                 ast_copy_flags(&features, &(config->features_callee), AST_FLAGS_ALL);
1897                 dynamic_features = pbx_builtin_getvar_helper(peer, "DYNAMIC_FEATURES");
1898         }
1899         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);
1900
1901         ast_rwlock_rdlock(&features_lock);
1902         for (x = 0; x < FEATURES_COUNT; x++) {
1903                 if ((ast_test_flag(&features, builtin_features[x].feature_mask)) &&
1904                     !ast_strlen_zero(builtin_features[x].exten)) {
1905                         /* Feature is up for consideration */
1906                         if (!strcmp(builtin_features[x].exten, code)) {
1907                                 res = builtin_features[x].operation(chan, peer, config, code, sense, NULL);
1908                                 feature_detected = 1;
1909                                 break;
1910                         } else if (!strncmp(builtin_features[x].exten, code, strlen(code))) {
1911                                 if (res == AST_FEATURE_RETURN_PASSDIGITS)
1912                                         res = AST_FEATURE_RETURN_STOREDIGITS;
1913                         }
1914                 }
1915         }
1916         ast_rwlock_unlock(&features_lock);
1917
1918         if (ast_strlen_zero(dynamic_features) || feature_detected)
1919                 return res;
1920
1921         tmp = ast_strdupa(dynamic_features);
1922
1923         while ((tok = strsep(&tmp, "#"))) {
1924                 AST_RWLIST_RDLOCK(&feature_groups);
1925
1926                 fg = find_group(tok);
1927
1928                 if (fg) {
1929                         AST_LIST_TRAVERSE(&fg->features, fge, entry) {
1930                                 if (strcasecmp(fge->exten, code))
1931                                         continue;
1932
1933                                 res = fge->feature->operation(chan, peer, config, code, sense, fge->feature);
1934                                 if (res != AST_FEATURE_RETURN_KEEPTRYING) {
1935                                         AST_RWLIST_UNLOCK(&feature_groups);
1936                                         break;
1937                                 }
1938                                 res = AST_FEATURE_RETURN_PASSDIGITS;
1939                         }
1940                         if (fge)
1941                                 break;
1942                 }
1943
1944                 AST_RWLIST_UNLOCK(&feature_groups);
1945
1946                 AST_RWLIST_RDLOCK(&feature_list);
1947
1948                 if (!(feature = find_dynamic_feature(tok))) {
1949                         AST_RWLIST_UNLOCK(&feature_list);
1950                         continue;
1951                 }
1952                         
1953                 /* Feature is up for consideration */
1954                 if (!strcmp(feature->exten, code)) {
1955                         ast_verb(3, " Feature Found: %s exten: %s\n",feature->sname, tok);
1956                         res = feature->operation(chan, peer, config, code, sense, feature);
1957                         if (res != AST_FEATURE_RETURN_KEEPTRYING) {
1958                                 AST_RWLIST_UNLOCK(&feature_list);
1959                                 break;
1960                         }
1961                         res = AST_FEATURE_RETURN_PASSDIGITS;
1962                 } else if (!strncmp(feature->exten, code, strlen(code)))
1963                         res = AST_FEATURE_RETURN_STOREDIGITS;
1964
1965                 AST_RWLIST_UNLOCK(&feature_list);
1966         }
1967         
1968         return res;
1969 }
1970
1971 static void set_config_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
1972 {
1973         int x;
1974         
1975         ast_clear_flag(config, AST_FLAGS_ALL);
1976
1977         ast_rwlock_rdlock(&features_lock);
1978         for (x = 0; x < FEATURES_COUNT; x++) {
1979                 if (!ast_test_flag(builtin_features + x, AST_FEATURE_FLAG_NEEDSDTMF))
1980                         continue;
1981
1982                 if (ast_test_flag(&(config->features_caller), builtin_features[x].feature_mask))
1983                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
1984
1985                 if (ast_test_flag(&(config->features_callee), builtin_features[x].feature_mask))
1986                         ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
1987         }
1988         ast_rwlock_unlock(&features_lock);
1989         
1990         if (chan && peer && !(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
1991                 const char *dynamic_features = pbx_builtin_getvar_helper(chan, "DYNAMIC_FEATURES");
1992
1993                 if (dynamic_features) {
1994                         char *tmp = ast_strdupa(dynamic_features);
1995                         char *tok;
1996                         struct ast_call_feature *feature;
1997
1998                         /* while we have a feature */
1999                         while ((tok = strsep(&tmp, "#"))) {
2000                                 AST_RWLIST_RDLOCK(&feature_list);
2001                                 if ((feature = find_dynamic_feature(tok)) && ast_test_flag(feature, AST_FEATURE_FLAG_NEEDSDTMF)) {
2002                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLER))
2003                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
2004                                         if (ast_test_flag(feature, AST_FEATURE_FLAG_BYCALLEE))
2005                                                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
2006                                 }
2007                                 AST_RWLIST_UNLOCK(&feature_list);
2008                         }
2009                 }
2010         }
2011 }
2012
2013 /*! 
2014  * \brief Get feature and dial
2015  * \param caller,transferee,type,format,data,timeout,outstate,cid_num,cid_name,igncallerstate
2016  *
2017  * Request channel, set channel variables, initiate call,check if they want to disconnect
2018  * go into loop, check if timeout has elapsed, check if person to be transfered hung up,
2019  * check for answer break loop, set cdr return channel.
2020  *
2021  * \todo XXX Check - this is very similar to the code in channel.c 
2022  * \return always a channel
2023 */
2024 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)
2025 {
2026         int state = 0;
2027         int cause = 0;
2028         int to;
2029         struct ast_channel *chan;
2030         struct ast_channel *monitor_chans[2];
2031         struct ast_channel *active_channel;
2032         int res = 0, ready = 0;
2033         struct timeval started;
2034         int x, len = 0;
2035         char *disconnect_code = NULL, *dialed_code = NULL;
2036
2037         if (!(chan = ast_request(type, format, data, &cause))) {
2038                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2039                 switch(cause) {
2040                 case AST_CAUSE_BUSY:
2041                         state = AST_CONTROL_BUSY;
2042                         break;
2043                 case AST_CAUSE_CONGESTION:
2044                         state = AST_CONTROL_CONGESTION;
2045                         break;
2046                 }
2047                 goto done;
2048         }
2049
2050         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2051         ast_string_field_set(chan, language, language);
2052         ast_channel_inherit_variables(caller, chan);    
2053         pbx_builtin_setvar_helper(chan, "TRANSFERERNAME", caller->name);
2054                 
2055         if (ast_call(chan, data, timeout)) {
2056                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2057                 goto done;
2058         }
2059         
2060         ast_indicate(caller, AST_CONTROL_RINGING);
2061         /* support dialing of the featuremap disconnect code while performing an attended tranfer */
2062         ast_rwlock_rdlock(&features_lock);
2063         for (x = 0; x < FEATURES_COUNT; x++) {
2064                 if (strcasecmp(builtin_features[x].sname, "disconnect"))
2065                         continue;
2066
2067                 disconnect_code = builtin_features[x].exten;
2068                 len = strlen(disconnect_code) + 1;
2069                 dialed_code = alloca(len);
2070                 memset(dialed_code, 0, len);
2071                 break;
2072         }
2073         ast_rwlock_unlock(&features_lock);
2074         x = 0;
2075         started = ast_tvnow();
2076         to = timeout;
2077
2078         ast_poll_channel_add(caller, chan);
2079
2080         while (!((transferee && ast_check_hangup(transferee)) && (!igncallerstate && ast_check_hangup(caller))) && timeout && (chan->_state != AST_STATE_UP)) {
2081                 struct ast_frame *f = NULL;
2082
2083                 monitor_chans[0] = caller;
2084                 monitor_chans[1] = chan;
2085                 active_channel = ast_waitfor_n(monitor_chans, 2, &to);
2086
2087                 /* see if the timeout has been violated */
2088                 if(ast_tvdiff_ms(ast_tvnow(), started) > timeout) {
2089                         state = AST_CONTROL_UNHOLD;
2090                         ast_log(LOG_NOTICE, "We exceeded our AT-timeout\n");
2091                         break; /*doh! timeout*/
2092                 }
2093
2094                 if (!active_channel)
2095                         continue;
2096
2097                 if (chan && (chan == active_channel)){
2098                         f = ast_read(chan);
2099                         if (f == NULL) { /*doh! where'd he go?*/
2100                                 state = AST_CONTROL_HANGUP;
2101                                 res = 0;
2102                                 break;
2103                         }
2104                         
2105                         if (f->frametype == AST_FRAME_CONTROL || f->frametype == AST_FRAME_DTMF || f->frametype == AST_FRAME_TEXT) {
2106                                 if (f->subclass == AST_CONTROL_RINGING) {
2107                                         state = f->subclass;
2108                                         ast_verb(3, "%s is ringing\n", chan->name);
2109                                         ast_indicate(caller, AST_CONTROL_RINGING);
2110                                 } else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2111                                         state = f->subclass;
2112                                         ast_verb(3, "%s is busy\n", chan->name);
2113                                         ast_indicate(caller, AST_CONTROL_BUSY);
2114                                         ast_frfree(f);
2115                                         f = NULL;
2116                                         break;
2117                                 } else if (f->subclass == AST_CONTROL_ANSWER) {
2118                                         /* This is what we are hoping for */
2119                                         state = f->subclass;
2120                                         ast_frfree(f);
2121                                         f = NULL;
2122                                         ready=1;
2123                                         break;
2124                                 } else if (f->subclass != -1) {
2125                                         ast_log(LOG_NOTICE, "Don't know what to do about control frame: %d\n", f->subclass);
2126                                 }
2127                                 /* else who cares */
2128                         }
2129
2130                 } else if (caller && (active_channel == caller)) {
2131                         f = ast_read(caller);
2132                         if (f == NULL) { /*doh! where'd he go?*/
2133                                 if (!igncallerstate) {
2134                                         if (ast_check_hangup(caller) && !ast_check_hangup(chan)) {
2135                                                 /* make this a blind transfer */
2136                                                 ready = 1;
2137                                                 break;
2138                                         }
2139                                         state = AST_CONTROL_HANGUP;
2140                                         res = 0;
2141                                         break;
2142                                 }
2143                         } else {
2144                         
2145                                 if (f->frametype == AST_FRAME_DTMF) {
2146                                         dialed_code[x++] = f->subclass;
2147                                         dialed_code[x] = '\0';
2148                                         if (strlen(dialed_code) == len) {
2149                                                 x = 0;
2150                                         } else if (x && strncmp(dialed_code, disconnect_code, x)) {
2151                                                 x = 0;
2152                                                 dialed_code[x] = '\0';
2153                                         }
2154                                         if (*dialed_code && !strcmp(dialed_code, disconnect_code)) {
2155                                                 /* Caller Canceled the call */
2156                                                 state = AST_CONTROL_UNHOLD;
2157                                                 ast_frfree(f);
2158                                                 f = NULL;
2159                                                 break;
2160                                         }
2161                                 }
2162                         }
2163                 }
2164                 if (f)
2165                         ast_frfree(f);
2166         } /* end while */
2167
2168         ast_poll_channel_del(caller, chan);
2169                 
2170 done:
2171         ast_indicate(caller, -1);
2172         if (chan && ready) {
2173                 if (chan->_state == AST_STATE_UP) 
2174                         state = AST_CONTROL_ANSWER;
2175                 res = 0;
2176         } else if (chan) {
2177                 res = -1;
2178                 ast_hangup(chan);
2179                 chan = NULL;
2180         } else {
2181                 res = -1;
2182         }
2183         
2184         if (outstate)
2185                 *outstate = state;
2186
2187         return chan;
2188 }
2189
2190 /*!
2191  * \brief return the first unlocked cdr in a possible chain
2192 */
2193 static struct ast_cdr *pick_unlocked_cdr(struct ast_cdr *cdr)
2194 {
2195         struct ast_cdr *cdr_orig = cdr;
2196         while (cdr) {
2197                 if (!ast_test_flag(cdr,AST_CDR_FLAG_LOCKED))
2198                         return cdr;
2199                 cdr = cdr->next;
2200         }
2201         return cdr_orig; /* everybody LOCKED or some other weirdness, like a NULL */
2202 }
2203
2204 /*!
2205  * \brief bridge the call and set CDR
2206  * \param chan,peer,config
2207  * 
2208  * Set start time, check for two channels,check if monitor on
2209  * check for feature activation, create new CDR
2210  * \retval res on success.
2211  * \retval -1 on failure to bridge.
2212 */
2213 int ast_bridge_call(struct ast_channel *chan,struct ast_channel *peer,struct ast_bridge_config *config)
2214 {
2215         /* Copy voice back and forth between the two channels.  Give the peer
2216            the ability to transfer calls with '#<extension' syntax. */
2217         struct ast_frame *f;
2218         struct ast_channel *who;
2219         char chan_featurecode[FEATURE_MAX_LEN + 1]="";
2220         char peer_featurecode[FEATURE_MAX_LEN + 1]="";
2221         char orig_channame[AST_MAX_EXTENSION];
2222         char orig_peername[AST_MAX_EXTENSION];
2223         int res;
2224         int diff;
2225         int hasfeatures=0;
2226         int hadfeatures=0;
2227         int autoloopflag;
2228         struct ast_option_header *aoh;
2229         struct ast_bridge_config backup_config;
2230         struct ast_cdr *bridge_cdr = NULL;
2231         struct ast_cdr *orig_peer_cdr = NULL;
2232         struct ast_cdr *chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2233         struct ast_cdr *peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2234         struct ast_cdr *new_chan_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2235         struct ast_cdr *new_peer_cdr = NULL; /* the proper chan cdr, if there are forked cdrs */
2236
2237         memset(&backup_config, 0, sizeof(backup_config));
2238
2239         config->start_time = ast_tvnow();
2240
2241         if (chan && peer) {
2242                 pbx_builtin_setvar_helper(chan, "BRIDGEPEER", peer->name);
2243                 pbx_builtin_setvar_helper(peer, "BRIDGEPEER", chan->name);
2244         } else if (chan) {
2245                 pbx_builtin_setvar_helper(chan, "BLINDTRANSFER", NULL);
2246         }
2247
2248         /* This is an interesting case.  One example is if a ringing channel gets redirected to
2249          * an extension that picks up a parked call.  This will make sure that the call taken
2250          * out of parking gets told that the channel it just got bridged to is still ringing. */
2251         if (chan->_state == AST_STATE_RINGING && peer->visible_indication != AST_CONTROL_RINGING) {
2252                 ast_indicate(peer, AST_CONTROL_RINGING);
2253         }
2254
2255         if (monitor_ok) {
2256                 const char *monitor_exec;
2257                 struct ast_channel *src = NULL;
2258                 if (!monitor_app) { 
2259                         if (!(monitor_app = pbx_findapp("Monitor")))
2260                                 monitor_ok=0;
2261                 }
2262                 if ((monitor_exec = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR"))) 
2263                         src = chan;
2264                 else if ((monitor_exec = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR")))
2265                         src = peer;
2266                 if (monitor_app && src) {
2267                         char *tmp = ast_strdupa(monitor_exec);
2268                         pbx_exec(src, monitor_app, tmp);
2269                 }
2270         }
2271         
2272         set_config_flags(chan, peer, config);
2273         config->firstpass = 1;
2274
2275         /* Answer if need be */
2276         if (ast_answer(chan))
2277                 return -1;
2278
2279         ast_copy_string(orig_channame,chan->name,sizeof(orig_channame));
2280         ast_copy_string(orig_peername,peer->name,sizeof(orig_peername));
2281         orig_peer_cdr = peer_cdr;
2282         
2283         if (!chan_cdr || (chan_cdr && !ast_test_flag(chan_cdr, AST_CDR_FLAG_POST_DISABLED))) {
2284                 
2285                 if (chan_cdr) {
2286                         ast_set_flag(chan_cdr, AST_CDR_FLAG_MAIN);
2287                         ast_cdr_update(chan);
2288                         bridge_cdr = ast_cdr_dup(chan_cdr);
2289                         ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
2290                         ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
2291                 } else {
2292                         /* better yet, in a xfer situation, find out why the chan cdr got zapped (pun unintentional) */
2293                         bridge_cdr = ast_cdr_alloc(); /* this should be really, really rare/impossible? */
2294                         ast_copy_string(bridge_cdr->channel, chan->name, sizeof(bridge_cdr->channel));
2295                         ast_copy_string(bridge_cdr->dstchannel, peer->name, sizeof(bridge_cdr->dstchannel));
2296                         ast_copy_string(bridge_cdr->uniqueid, chan->uniqueid, sizeof(bridge_cdr->uniqueid));
2297                         ast_copy_string(bridge_cdr->lastapp, chan->appl, sizeof(bridge_cdr->lastapp));
2298                         ast_copy_string(bridge_cdr->lastdata, chan->data, sizeof(bridge_cdr->lastdata));
2299                         ast_cdr_setcid(bridge_cdr, chan);
2300                         bridge_cdr->disposition = (chan->_state == AST_STATE_UP) ?  AST_CDR_ANSWERED : AST_CDR_NULL;
2301                         bridge_cdr->amaflags = chan->amaflags ? chan->amaflags :  ast_default_amaflags;
2302                         ast_copy_string(bridge_cdr->accountcode, chan->accountcode, sizeof(bridge_cdr->accountcode));
2303                         /* Destination information */
2304                         ast_copy_string(bridge_cdr->dst, chan->exten, sizeof(bridge_cdr->dst));
2305                         ast_copy_string(bridge_cdr->dcontext, chan->context, sizeof(bridge_cdr->dcontext));
2306                         if (peer_cdr) {
2307                                 bridge_cdr->start = peer_cdr->start;
2308                                 ast_copy_string(bridge_cdr->userfield, peer_cdr->userfield, sizeof(bridge_cdr->userfield));
2309                         } else {
2310                                 ast_cdr_start(bridge_cdr);
2311                         }
2312                 }
2313                 ast_debug(4,"bridge answer set, chan answer set\n");
2314                 /* peer_cdr->answer will be set when a macro runs on the peer;
2315                    in that case, the bridge answer will be delayed while the
2316                    macro plays on the peer channel. The peer answered the call
2317                    before the macro started playing. To the phone system,
2318                    this is billable time for the call, even tho the caller
2319                    hears nothing but ringing while the macro does its thing. */
2320                 if (peer_cdr && !ast_tvzero(peer_cdr->answer)) {
2321                         bridge_cdr->answer = peer_cdr->answer;
2322                         chan_cdr->answer = peer_cdr->answer;
2323                         bridge_cdr->disposition = peer_cdr->disposition;
2324                         chan_cdr->disposition = peer_cdr->disposition;
2325                 } else {
2326                         ast_cdr_answer(bridge_cdr);
2327                         ast_cdr_answer(chan_cdr); /* for the sake of cli status checks */
2328                 }
2329                 if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2330                         ast_set_flag(chan_cdr, AST_CDR_FLAG_BRIDGED);
2331                         if (peer_cdr) {
2332                                 ast_set_flag(peer_cdr, AST_CDR_FLAG_BRIDGED);
2333                         }
2334                 }
2335         }
2336         for (;;) {
2337                 struct ast_channel *other;      /* used later */
2338                 
2339                 res = ast_channel_bridge(chan, peer, config, &f, &who);
2340
2341                 if (config->feature_timer) {
2342                         /* Update time limit for next pass */
2343                         diff = ast_tvdiff_ms(ast_tvnow(), config->start_time);
2344                         config->feature_timer -= diff;
2345                         if (hasfeatures) {
2346                                 /* Running on backup config, meaning a feature might be being
2347                                    activated, but that's no excuse to keep things going 
2348                                    indefinitely! */
2349                                 if (backup_config.feature_timer && ((backup_config.feature_timer -= diff) <= 0)) {
2350                                         ast_debug(1, "Timed out, realtime this time!\n");
2351                                         config->feature_timer = 0;
2352                                         who = chan;
2353                                         if (f)
2354                                                 ast_frfree(f);
2355                                         f = NULL;
2356                                         res = 0;
2357                                 } else if (config->feature_timer <= 0) {
2358                                         /* Not *really* out of time, just out of time for
2359                                            digits to come in for features. */
2360                                         ast_debug(1, "Timed out for feature!\n");
2361                                         if (!ast_strlen_zero(peer_featurecode)) {
2362                                                 ast_dtmf_stream(chan, peer, peer_featurecode, 0, 0);
2363                                                 memset(peer_featurecode, 0, sizeof(peer_featurecode));
2364                                         }
2365                                         if (!ast_strlen_zero(chan_featurecode)) {
2366                                                 ast_dtmf_stream(peer, chan, chan_featurecode, 0, 0);
2367                                                 memset(chan_featurecode, 0, sizeof(chan_featurecode));
2368                                         }
2369                                         if (f)
2370                                                 ast_frfree(f);
2371                                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2372                                         if (!hasfeatures) {
2373                                                 /* Restore original (possibly time modified) bridge config */
2374                                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
2375                                                 memset(&backup_config, 0, sizeof(backup_config));
2376                                         }
2377                                         hadfeatures = hasfeatures;
2378                                         /* Continue as we were */
2379                                         continue;
2380                                 } else if (!f) {
2381                                         /* The bridge returned without a frame and there is a feature in progress.
2382                                          * However, we don't think the feature has quite yet timed out, so just
2383                                          * go back into the bridge. */
2384                                         continue;
2385                                 }
2386                         } else {
2387                                 if (config->feature_timer <=0) {
2388                                         /* We ran out of time */
2389                                         config->feature_timer = 0;
2390                                         who = chan;
2391                                         if (f)
2392                                                 ast_frfree(f);
2393                                         f = NULL;
2394                                         res = 0;
2395                                 }
2396                         }
2397                 }
2398                 if (res < 0) {
2399                         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_test_flag(peer, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan) && !ast_check_hangup(peer))
2400                                 ast_log(LOG_WARNING, "Bridge failed on channels %s and %s\n", chan->name, peer->name);
2401                         goto before_you_go;
2402                 }
2403                 
2404                 if (!f || (f->frametype == AST_FRAME_CONTROL &&
2405                                 (f->subclass == AST_CONTROL_HANGUP || f->subclass == AST_CONTROL_BUSY || 
2406                                         f->subclass == AST_CONTROL_CONGESTION))) {
2407                         res = -1;
2408                         break;
2409                 }
2410                 /* many things should be sent to the 'other' channel */
2411                 other = (who == chan) ? peer : chan;
2412                 if (f->frametype == AST_FRAME_CONTROL) {
2413                         switch (f->subclass) {
2414                         case AST_CONTROL_RINGING:
2415                         case AST_CONTROL_FLASH:
2416                         case -1:
2417                                 ast_indicate(other, f->subclass);
2418                                 break;
2419                         case AST_CONTROL_HOLD:
2420                         case AST_CONTROL_UNHOLD:
2421                                 ast_indicate_data(other, f->subclass, f->data.ptr, f->datalen);
2422                                 break;
2423                         case AST_CONTROL_OPTION:
2424                                 aoh = f->data.ptr;
2425                                 /* Forward option Requests */
2426                                 if (aoh && aoh->flag == AST_OPTION_FLAG_REQUEST) {
2427                                         ast_channel_setoption(other, ntohs(aoh->option), aoh->data, 
2428                                                 f->datalen - sizeof(struct ast_option_header), 0);
2429                                 }
2430                                 break;
2431                         }
2432                 } else if (f->frametype == AST_FRAME_DTMF_BEGIN) {
2433                         /* eat it */
2434                 } else if (f->frametype == AST_FRAME_DTMF) {
2435                         char *featurecode;
2436                         int sense;
2437
2438                         hadfeatures = hasfeatures;
2439                         /* This cannot overrun because the longest feature is one shorter than our buffer */
2440                         if (who == chan) {
2441                                 sense = FEATURE_SENSE_CHAN;
2442                                 featurecode = chan_featurecode;
2443                         } else  {
2444                                 sense = FEATURE_SENSE_PEER;
2445                                 featurecode = peer_featurecode;
2446                         }
2447                         /*! append the event to featurecode. we rely on the string being zero-filled, and
2448                          * not overflowing it. 
2449                          * \todo XXX how do we guarantee the latter ?
2450                          */
2451                         featurecode[strlen(featurecode)] = f->subclass;
2452                         /* Get rid of the frame before we start doing "stuff" with the channels */
2453                         ast_frfree(f);
2454                         f = NULL;
2455                         config->feature_timer = backup_config.feature_timer;
2456                         res = ast_feature_interpret(chan, peer, config, featurecode, sense);
2457                         switch(res) {
2458                         case AST_FEATURE_RETURN_PASSDIGITS:
2459                                 ast_dtmf_stream(other, who, featurecode, 0, 0);
2460                                 /* Fall through */
2461                         case AST_FEATURE_RETURN_SUCCESS:
2462                                 memset(featurecode, 0, sizeof(chan_featurecode));
2463                                 break;
2464                         }
2465                         if (res >= AST_FEATURE_RETURN_PASSDIGITS) {
2466                                 res = 0;
2467                         } else 
2468                                 break;
2469                         hasfeatures = !ast_strlen_zero(chan_featurecode) || !ast_strlen_zero(peer_featurecode);
2470                         if (hadfeatures && !hasfeatures) {
2471                                 /* Restore backup */
2472                                 memcpy(config, &backup_config, sizeof(struct ast_bridge_config));
2473                                 memset(&backup_config, 0, sizeof(struct ast_bridge_config));
2474                         } else if (hasfeatures) {
2475                                 if (!hadfeatures) {
2476                                         /* Backup configuration */
2477                                         memcpy(&backup_config, config, sizeof(struct ast_bridge_config));
2478                                         /* Setup temporary config options */
2479                                         config->play_warning = 0;
2480                                         ast_clear_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
2481                                         ast_clear_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
2482                                         config->warning_freq = 0;
2483                                         config->warning_sound = NULL;
2484                                         config->end_sound = NULL;
2485                                         config->start_sound = NULL;
2486                                         config->firstpass = 0;
2487                                 }
2488                                 config->start_time = ast_tvnow();
2489                                 config->feature_timer = featuredigittimeout;
2490                                 ast_debug(1, "Set time limit to %ld\n", config->feature_timer);
2491                         }
2492                 }
2493                 if (f)
2494                         ast_frfree(f);
2495
2496         }
2497    before_you_go:
2498
2499         if (ast_test_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT)) {
2500                 ast_clear_flag(chan,AST_FLAG_BRIDGE_HANGUP_DONT); /* its job is done */
2501                 if (bridge_cdr) {
2502                         ast_cdr_discard(bridge_cdr);
2503                         /* QUESTION: should we copy bridge_cdr fields to the peer before we throw it away? */
2504                 }
2505                 return res; /* if we shouldn't do the h-exten, we shouldn't do the bridge cdr, either! */
2506         }
2507
2508         if (config->end_bridge_callback) {
2509                 config->end_bridge_callback(config->end_bridge_callback_data);
2510         }
2511
2512         /* run the hangup exten on the chan object IFF it was NOT involved in a parking situation 
2513          * if it were, then chan belongs to a different thread now, and might have been hung up long
2514      * ago.
2515          */
2516         if (!ast_test_flag(&(config->features_caller),AST_FEATURE_NO_H_EXTEN) &&
2517                 ast_exists_extension(chan, chan->context, "h", 1, chan->cid.cid_num)) {
2518                 struct ast_cdr *swapper = NULL;
2519                 char savelastapp[AST_MAX_EXTENSION];
2520                 char savelastdata[AST_MAX_EXTENSION];
2521                 char save_exten[AST_MAX_EXTENSION];
2522                 int  save_prio;
2523                 int  found = 0; /* set if we find at least one match */
2524                 int  spawn_error = 0;
2525                 
2526                 autoloopflag = ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP);
2527                 ast_set_flag(chan, AST_FLAG_IN_AUTOLOOP);
2528                 if (bridge_cdr && ast_opt_end_cdr_before_h_exten) {
2529                         ast_cdr_end(bridge_cdr);
2530                 }
2531                 /* swap the bridge cdr and the chan cdr for a moment, and let the endbridge
2532                    dialplan code operate on it */
2533                 ast_channel_lock(chan);
2534                 if (bridge_cdr) {
2535                         swapper = chan->cdr;
2536                         ast_copy_string(savelastapp, bridge_cdr->lastapp, sizeof(bridge_cdr->lastapp));
2537                         ast_copy_string(savelastdata, bridge_cdr->lastdata, sizeof(bridge_cdr->lastdata));
2538                         chan->cdr = bridge_cdr;
2539                 }
2540                 ast_copy_string(save_exten, chan->exten, sizeof(save_exten));
2541                 save_prio = chan->priority;
2542                 ast_copy_string(chan->exten, "h", sizeof(chan->exten));
2543                 chan->priority = 1;
2544                 ast_channel_unlock(chan);
2545                 while ((spawn_error = ast_spawn_extension(chan, chan->context, chan->exten, chan->priority, chan->cid.cid_num, &found, 1)) == 0) {
2546                         chan->priority++;
2547                 }
2548                 if (found && spawn_error) {
2549                         /* Something bad happened, or a hangup has been requested. */
2550                         ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2551                         ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", chan->context, chan->exten, chan->priority, chan->name);
2552                 }
2553                 /* swap it back */
2554                 ast_channel_lock(chan);
2555                 ast_copy_string(chan->exten, save_exten, sizeof(chan->exten));
2556                 chan->priority = save_prio;
2557                 if (bridge_cdr)
2558                         chan->cdr = swapper;
2559                 ast_set_flag(chan, AST_FLAG_BRIDGE_HANGUP_RUN);
2560                 ast_channel_unlock(chan);
2561                 /* protect the lastapp/lastdata against the effects of the hangup/dialplan code */
2562                 if (bridge_cdr) {
2563                         ast_copy_string(bridge_cdr->lastapp, savelastapp, sizeof(bridge_cdr->lastapp));
2564                         ast_copy_string(bridge_cdr->lastdata, savelastdata, sizeof(bridge_cdr->lastdata));
2565                 }
2566                 ast_set2_flag(chan, autoloopflag, AST_FLAG_IN_AUTOLOOP);
2567         }
2568         
2569         /* obey the NoCDR() wishes. -- move the DISABLED flag to the bridge CDR if it was set on the channel during the bridge... */
2570         new_chan_cdr = pick_unlocked_cdr(chan->cdr); /* the proper chan cdr, if there are forked cdrs */
2571         if (bridge_cdr && new_chan_cdr && ast_test_flag(new_chan_cdr, AST_CDR_FLAG_POST_DISABLED))
2572                 ast_set_flag(bridge_cdr, AST_CDR_FLAG_POST_DISABLED);
2573
2574         /* we can post the bridge CDR at this point */
2575         if (bridge_cdr) {
2576                 ast_cdr_end(bridge_cdr);
2577                 ast_cdr_detach(bridge_cdr);
2578         }
2579         
2580         /* do a specialized reset on the beginning channel
2581            CDR's, if they still exist, so as not to mess up
2582            issues in future bridges;
2583            
2584            Here are the rules of the game:
2585            1. The chan and peer channel pointers will not change
2586               during the life of the bridge.
2587            2. But, in transfers, the channel names will change.
2588               between the time the bridge is started, and the
2589               time the channel ends. 
2590               Usually, when a channel changes names, it will
2591               also change CDR pointers.
2592            3. Usually, only one of the two channels (chan or peer)
2593               will change names.
2594            4. Usually, if a channel changes names during a bridge,
2595               it is because of a transfer. Usually, in these situations,
2596               it is normal to see 2 bridges running simultaneously, and
2597               it is not unusual to see the two channels that change
2598               swapped between bridges.
2599            5. After a bridge occurs, we have 2 or 3 channels' CDRs
2600               to attend to; if the chan or peer changed names,
2601               we have the before and after attached CDR's.
2602         */
2603         
2604         if (new_chan_cdr) {
2605                 struct ast_channel *chan_ptr = NULL;
2606  
2607                 if (strcasecmp(orig_channame, chan->name) != 0) { 
2608                         /* old channel */
2609                         chan_ptr = ast_get_channel_by_name_locked(orig_channame);
2610                         if (chan_ptr) {
2611                                 if (!ast_bridged_channel(chan_ptr)) {
2612                                         struct ast_cdr *cur;
2613                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2614                                                 if (cur == chan_cdr) {
2615                                                         break;
2616                                                 }
2617                                         }
2618                                         if (cur)
2619                                                 ast_cdr_specialized_reset(chan_cdr,0);
2620                                 }
2621                                 ast_channel_unlock(chan_ptr);
2622                         }
2623                         /* new channel */
2624                         ast_cdr_specialized_reset(new_chan_cdr,0);
2625                 } else {
2626                         ast_cdr_specialized_reset(chan_cdr,0); /* nothing changed, reset the chan_cdr  */
2627                 }
2628         }
2629         
2630         {
2631                 struct ast_channel *chan_ptr = NULL;
2632                 new_peer_cdr = pick_unlocked_cdr(peer->cdr); /* the proper chan cdr, if there are forked cdrs */
2633                 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))
2634                         ast_set_flag(new_peer_cdr, AST_CDR_FLAG_POST_DISABLED); /* DISABLED is viral-- it will propagate across a bridge */
2635                 if (strcasecmp(orig_peername, peer->name) != 0) { 
2636                         /* old channel */
2637                         chan_ptr = ast_get_channel_by_name_locked(orig_peername);
2638                         if (chan_ptr) {
2639                                 if (!ast_bridged_channel(chan_ptr)) {
2640                                         struct ast_cdr *cur;
2641                                         for (cur = chan_ptr->cdr; cur; cur = cur->next) {
2642                                                 if (cur == peer_cdr) {
2643                                                         break;
2644                                                 }
2645                                         }
2646                                         if (cur)
2647                                                 ast_cdr_specialized_reset(peer_cdr,0);
2648                                 }
2649                                 ast_channel_unlock(chan_ptr);
2650                         }
2651                         /* new channel */
2652                         ast_cdr_specialized_reset(new_peer_cdr,0);
2653                 } else {
2654                         ast_cdr_specialized_reset(peer_cdr,0); /* nothing changed, reset the peer_cdr  */
2655                 }
2656         }
2657         
2658         return res;
2659 }
2660
2661 /*! \brief Output parking event to manager */
2662 static void post_manager_event(const char *s, struct parkeduser *pu)
2663 {
2664         manager_event(EVENT_FLAG_CALL, s,
2665                 "Exten: %s\r\n"
2666                 "Channel: %s\r\n"
2667                 "Parkinglot: %s\r\n"
2668                 "CallerIDNum: %s\r\n"
2669                 "CallerIDName: %s\r\n"
2670                 "UniqueID: %s\r\n\r\n",
2671                 pu->parkingexten, 
2672                 pu->chan->name,
2673                 pu->parkinglot->name,
2674                 S_OR(pu->chan->cid.cid_num, "<unknown>"),
2675                 S_OR(pu->chan->cid.cid_name, "<unknown>"),
2676                 pu->chan->uniqueid
2677                 );
2678 }
2679
2680 /*! \brief Run management on parkinglots, called once per parkinglot */
2681 int manage_parkinglot(struct ast_parkinglot *curlot, fd_set *rfds, fd_set *efds, fd_set *nrfds, fd_set *nefds, int *ms, int *max)
2682 {
2683
2684         struct parkeduser *pu;
2685         int res = 0;
2686         char parkingslot[AST_MAX_EXTENSION];
2687
2688         /* Lock parking list */
2689         AST_LIST_LOCK(&curlot->parkings);
2690         AST_LIST_TRAVERSE_SAFE_BEGIN(&curlot->parkings, pu, list) {
2691                 struct ast_channel *chan = pu->chan;    /* shorthand */
2692                 int tms;        /* timeout for this item */
2693                 int x;          /* fd index in channel */
2694                 struct ast_context *con;
2695
2696                 if (pu->notquiteyet) { /* Pretend this one isn't here yet */
2697                         continue;
2698                 }
2699                 tms = ast_tvdiff_ms(ast_tvnow(), pu->start);
2700                 if (tms > pu->parkingtime) {
2701                         /* Stop music on hold */
2702                         ast_indicate(pu->chan, AST_CONTROL_UNHOLD);
2703                         /* Get chan, exten from derived kludge */
2704                         if (pu->peername[0]) {
2705                                 char *peername = ast_strdupa(pu->peername);
2706                                 char *cp = strrchr(peername, '-');
2707                                 char peername_flat[AST_MAX_EXTENSION]; /* using something like DAHDI/52 for an extension name is NOT a good idea */
2708                                 int i;
2709
2710                                 if (cp) 
2711                                         *cp = 0;
2712                                 ast_copy_string(peername_flat,peername,sizeof(peername_flat));
2713                                 for(i=0; peername_flat[i] && i < AST_MAX_EXTENSION; i++) {
2714                                         if (peername_flat[i] == '/') 
2715                                                 peername_flat[i]= '0';
2716                                 }
2717                                 con = ast_context_find_or_create(NULL, NULL, pu->parkinglot->parking_con_dial, registrar);
2718                                 if (!con) {
2719                                         ast_log(LOG_ERROR, "Parking dial context '%s' does not exist and unable to create\n", pu->parkinglot->parking_con_dial);
2720                                 }
2721                                 if (con) {
2722                                         char returnexten[AST_MAX_EXTENSION];
2723                                         struct ast_datastore *features_datastore;
2724                                         struct ast_dial_features *dialfeatures = NULL;
2725
2726                                         ast_channel_lock(chan);
2727
2728                                         if ((features_datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL)))
2729                                                 dialfeatures = features_datastore->data;
2730
2731                                         ast_channel_unlock(chan);
2732
2733                                         if (!strncmp(peername, "Parked/", 7)) {
2734                                                 peername += 7;
2735                                         }
2736
2737                                         if (dialfeatures)
2738                                                 snprintf(returnexten, sizeof(returnexten), "%s,,%s", peername, dialfeatures->options);
2739                                         else /* Existing default */
2740                                                 snprintf(returnexten, sizeof(returnexten), "%s,,t", peername);
2741
2742                                         ast_add_extension2(con, 1, peername_flat, 1, NULL, NULL, "Dial", ast_strdup(returnexten), ast_free_ptr, registrar);
2743                                 }
2744                                 if (comebacktoorigin) {
2745                                         set_c_e_p(chan, pu->parkinglot->parking_con_dial, peername_flat, 1);
2746                                 } else {
2747                                         ast_log(LOG_WARNING, "now going to parkedcallstimeout,s,1 | ps is %d\n",pu->parkingnum);
2748                                         snprintf(parkingslot, sizeof(parkingslot), "%d", pu->parkingnum);
2749                                         pbx_builtin_setvar_helper(chan, "PARKINGSLOT", parkingslot);
2750                                         set_c_e_p(chan, "parkedcallstimeout", peername_flat, 1);
2751                                 }
2752                         } else {
2753                                 /* They've been waiting too long, send them back to where they came.  Theoretically they
2754                                    should have their original extensions and such, but we copy to be on the safe side */
2755                                 set_c_e_p(chan, pu->context, pu->exten, pu->priority);
2756                         }
2757                         post_manager_event("ParkedCallTimeOut", pu);
2758
2759                         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);
2760                         /* Start up the PBX, or hang them up */
2761                         if (ast_pbx_start(chan))  {
2762                                 ast_log(LOG_WARNING, "Unable to restart the PBX for user on '%s', hanging them up...\n", pu->chan->name);
2763                                 ast_hangup(chan);
2764                         }
2765                         /* And take them out of the parking lot */
2766                         con = ast_context_find(pu->parkinglot->parking_con);
2767                         if (con) {
2768                                 if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
2769                                         ast_log(LOG_WARNING, "Whoa, failed to remove the parking extension!\n");
2770                                 else
2771                                         notify_metermaids(pu->parkingexten, curlot->parking_con, AST_DEVICE_NOT_INUSE);
2772                         } else
2773                                 ast_log(LOG_WARNING, "Whoa, no parking context?\n");
2774                         AST_LIST_REMOVE_CURRENT(list);
2775                 } else {        /* still within parking time, process descriptors */
2776                         for (x = 0; x < AST_MAX_FDS; x++) {
2777                                 struct ast_frame *f;
2778
2779                                 if ((chan->fds[x] == -1) || (!FD_ISSET(chan->fds[x], rfds) && !FD_ISSET(pu->chan->fds[x], efds))) 
2780                                         continue;
2781                                 
2782                                 if (FD_ISSET(chan->fds[x], efds))
2783                                         ast_set_flag(chan, AST_FLAG_EXCEPTION);
2784                                 else
2785                                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
2786                                 chan->fdno = x;
2787
2788                                 /* See if they need servicing */
2789                                 f = ast_read(pu->chan);
2790                                 /* Hangup? */
2791                                 if (!f || ((f->frametype == AST_FRAME_CONTROL) && (f->subclass ==  AST_CONTROL_HANGUP))) {
2792                                         if (f)
2793                                                 ast_frfree(f);
2794                                         post_manager_event("ParkedCallGiveUp", pu);
2795
2796                                         /* There's a problem, hang them up*/
2797                                         ast_verb(2, "%s got tired of being parked\n", chan->name);
2798                                         ast_hangup(chan);
2799                                         /* And take them out of the parking lot */
2800                                         con = ast_context_find(curlot->parking_con);
2801                                         if (con) {
2802                                                 if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
2803                                                         ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
2804                                                 else
2805                                                         notify_metermaids(pu->parkingexten, curlot->parking_con, AST_DEVICE_NOT_INUSE);
2806                                         } else
2807                                                 ast_log(LOG_WARNING, "Whoa, no parking context for parking lot %s?\n", curlot->name);
2808                                         AST_LIST_REMOVE_CURRENT(list);
2809                                         break;
2810                                 } else {
2811                                         /* XXX Maybe we could do something with packets, like dial "0" for operator or something XXX */
2812                                         ast_frfree(f);
2813                                         if (pu->moh_trys < 3 && !chan->generatordata) {
2814                                                 ast_debug(1, "MOH on parked call stopped by outside source.  Restarting on channel %s.\n", chan->name);
2815                                                 ast_indicate_data(chan, AST_CONTROL_HOLD, 
2816                                                         S_OR(curlot->mohclass, NULL),
2817                                                         (!ast_strlen_zero(curlot->mohclass) ? strlen(curlot->mohclass) + 1 : 0));
2818                                                 pu->moh_trys++;
2819                                         }
2820                                         goto std;       /* XXX Ick: jumping into an else statement??? XXX */
2821                                 }
2822                         } /* End for */
2823                         if (x >= AST_MAX_FDS) {
2824 std:                            for (x=0; x<AST_MAX_FDS; x++) { /* mark fds for next round */
2825                                         if (chan->fds[x] > -1) {
2826                                                 FD_SET(chan->fds[x], nrfds);
2827                                                 FD_SET(chan->fds[x], nefds);
2828                                                 if (chan->fds[x] > *max)
2829                                                         *max = chan->fds[x];
2830                                         }
2831                                 }
2832                                 /* Keep track of our shortest wait */
2833                                 if (tms < *ms || *ms < 0)
2834                                         *ms = tms;
2835                         }
2836                 }
2837         }
2838         AST_LIST_TRAVERSE_SAFE_END;
2839         AST_LIST_UNLOCK(&curlot->parkings);
2840         return res;
2841 }
2842
2843 /*! 
2844  * \brief Take care of parked calls and unpark them if needed 
2845  * \param ignore unused var.
2846  * 
2847  * Start inf loop, lock parking lot, check if any parked channels have gone above timeout
2848  * if so, remove channel from parking lot and return it to the extension that parked it.
2849  * Check if parked channel decided to hangup, wait until next FD via select().
2850 */
2851 static void *do_parking_thread(void *ignore)
2852 {
2853         fd_set rfds, efds;      /* results from previous select, to be preserved across loops. */
2854         fd_set nrfds, nefds;    /* args for the next select */
2855         FD_ZERO(&rfds);
2856         FD_ZERO(&efds);
2857
2858         for (;;) {
2859                 int res = 0;
2860                 int ms = -1;    /* select timeout, uninitialized */
2861                 int max = -1;   /* max fd, none there yet */
2862                 struct ao2_iterator iter;
2863                 struct ast_parkinglot *curlot;
2864                 FD_ZERO(&nrfds);
2865                 FD_ZERO(&nefds);
2866                 iter = ao2_iterator_init(parkinglots, 0);
2867
2868                 while ((curlot = ao2_iterator_next(&iter))) {
2869                         res = manage_parkinglot(curlot, &rfds, &efds, &nrfds, &nefds, &ms, &max);
2870                         ao2_ref(curlot, -1);
2871                 }
2872
2873                 rfds = nrfds;
2874                 efds = nefds;
2875                 {
2876                         struct timeval wait = ast_samp2tv(ms, 1000);
2877                         /* Wait for something to happen */
2878                         ast_select(max + 1, &rfds, NULL, &efds, (ms > -1) ? &wait : NULL);
2879                 }
2880                 pthread_testcancel();
2881         }
2882         return NULL;    /* Never reached */
2883 }
2884
2885 /*! \brief Find parkinglot by name */
2886 struct ast_parkinglot *find_parkinglot(const char *name)
2887 {
2888         struct ast_parkinglot *parkinglot = NULL;
2889         struct ast_parkinglot tmp_parkinglot;
2890         
2891         if (ast_strlen_zero(name))
2892                 return NULL;
2893
2894         ast_copy_string(tmp_parkinglot.name, name, sizeof(tmp_parkinglot.name));
2895
2896         parkinglot = ao2_find(parkinglots, &tmp_parkinglot, OBJ_POINTER);
2897
2898         if (parkinglot && option_debug)
2899                 ast_log(LOG_DEBUG, "Found Parkinglot: %s\n", parkinglot->name);
2900
2901         return parkinglot;
2902 }
2903
2904 AST_APP_OPTIONS(park_call_options, BEGIN_OPTIONS
2905         AST_APP_OPTION('r', AST_PARK_OPT_RINGING),
2906         AST_APP_OPTION('R', AST_PARK_OPT_RANDOMIZE),
2907         AST_APP_OPTION('s', AST_PARK_OPT_SILENCE),
2908 END_OPTIONS );
2909
2910 /*! \brief Park a call */
2911 static int park_call_exec(struct ast_channel *chan, void *data)
2912 {
2913         /* Cache the original channel name in case we get masqueraded in the middle
2914          * of a park--it is still theoretically possible for a transfer to happen before
2915          * we get here, but it is _really_ unlikely */
2916         char *orig_chan_name = ast_strdupa(chan->name);
2917         char orig_exten[AST_MAX_EXTENSION];
2918         int orig_priority = chan->priority;
2919
2920         /* Data is unused at the moment but could contain a parking
2921            lot context eventually */
2922         int res = 0;
2923
2924         char *parse = NULL;
2925         AST_DECLARE_APP_ARGS(app_args,
2926                 AST_APP_ARG(timeout);
2927                 AST_APP_ARG(return_con);
2928                 AST_APP_ARG(return_ext);
2929                 AST_APP_ARG(return_pri);
2930                 AST_APP_ARG(options);
2931         );
2932
2933         parse = ast_strdupa(data);
2934         AST_STANDARD_APP_ARGS(app_args, parse);
2935
2936         ast_copy_string(orig_exten, chan->exten, sizeof(orig_exten));
2937
2938         /* Setup the exten/priority to be s/1 since we don't know
2939            where this call should return */
2940         strcpy(chan->exten, "s");
2941         chan->priority = 1;
2942
2943         /* Answer if call is not up */
2944         if (chan->_state != AST_STATE_UP)
2945                 res = ast_answer(chan);
2946
2947         /* Sleep to allow VoIP streams to settle down */
2948         if (!res)
2949                 res = ast_safe_sleep(chan, 1000);
2950
2951         /* Park the call */
2952         if (!res) {
2953                 struct ast_park_call_args args = {
2954                         .orig_chan_name = orig_chan_name,
2955                 };
2956                 struct ast_flags flags = { 0 };
2957
2958                 if (parse) {
2959                         if (!ast_strlen_zero(app_args.timeout)) {
2960                                 if (sscanf(app_args.timeout, "%d", &args.timeout) != 1) {
2961                                         ast_log(LOG_WARNING, "Invalid timeout '%s' provided\n", app_args.timeout);
2962                                         args.timeout = 0;
2963                                 }
2964                         }
2965                         if (!ast_strlen_zero(app_args.return_con)) {
2966                                 args.return_con = app_args.return_con;
2967                         }
2968                         if (!ast_strlen_zero(app_args.return_ext)) {
2969                                 args.return_ext = app_args.return_ext;
2970                         }
2971                         if (!ast_strlen_zero(app_args.return_pri)) {
2972                                 if (sscanf(app_args.return_pri, "%d", &args.return_pri) != 1) {
2973                                         ast_log(LOG_WARNING, "Invalid priority '%s' specified\n", app_args.return_pri);
2974                                         args.return_pri = 0;
2975                                 }
2976                         }
2977                 }
2978
2979                 ast_app_parse_options(park_call_options, &flags, NULL, app_args.options);
2980                 args.flags = flags.flags;
2981
2982                 res = masq_park_call_announce_args(chan, chan, &args);
2983                 /* Continue on in the dialplan */
2984                 if (res == 1) {
2985                         ast_copy_string(chan->exten, orig_exten, sizeof(chan->exten));
2986                         chan->priority = orig_priority;
2987                         res = 0;
2988                 } else if (!res) {
2989                         res = 1;
2990                 }
2991         }
2992
2993         return res;
2994 }
2995
2996 /*! \brief Pickup parked call */
2997 static int park_exec_full(struct ast_channel *chan, void *data, struct ast_parkinglot *parkinglot)
2998 {
2999         int res = 0;
3000         struct ast_channel *peer=NULL;
3001         struct parkeduser *pu;
3002         struct ast_context *con;
3003         int park = 0;
3004         struct ast_bridge_config config;
3005
3006         if (data)
3007                 park = atoi((char *)data);
3008
3009         parkinglot = find_parkinglot(findparkinglotname(chan));         
3010         if (!parkinglot)
3011                 parkinglot = default_parkinglot;
3012
3013         AST_LIST_LOCK(&parkinglot->parkings);
3014         AST_LIST_TRAVERSE_SAFE_BEGIN(&parkinglot->parkings, pu, list) {
3015                 if (!data || pu->parkingnum == park) {
3016                         if (pu->chan->pbx) { /* do not allow call to be picked up until the PBX thread is finished */
3017                                 AST_LIST_UNLOCK(&parkinglot->parkings);
3018                                 return -1;
3019                         }
3020                         AST_LIST_REMOVE_CURRENT(list);
3021                         break;
3022                 }
3023         }
3024         AST_LIST_TRAVERSE_SAFE_END
3025         AST_LIST_UNLOCK(&parkinglot->parkings);
3026
3027         if (pu) {
3028                 peer = pu->chan;
3029                 con = ast_context_find(parkinglot->parking_con);
3030                 if (con) {
3031                         if (ast_context_remove_extension2(con, pu->parkingexten, 1, NULL, 0))
3032                                 ast_log(LOG_WARNING, "Whoa, failed to remove the extension!\n");
3033                         else
3034                                 notify_metermaids(pu->parkingexten, parkinglot->parking_con, AST_DEVICE_NOT_INUSE);
3035                 } else
3036                         ast_log(LOG_WARNING, "Whoa, no parking context?\n");
3037
3038                 manager_event(EVENT_FLAG_CALL, "UnParkedCall",
3039                         "Exten: %s\r\n"
3040                         "Channel: %s\r\n"
3041                         "From: %s\r\n"
3042                         "CallerIDNum: %s\r\n"
3043                         "CallerIDName: %s\r\n",
3044                         pu->parkingexten, pu->chan->name, chan->name,
3045                         S_OR(pu->chan->cid.cid_num, "<unknown>"),
3046                         S_OR(pu->chan->cid.cid_name, "<unknown>")
3047                         );
3048
3049                 ast_free(pu);
3050         }
3051         /* JK02: it helps to answer the channel if not already up */
3052         if (chan->_state != AST_STATE_UP)
3053                 ast_answer(chan);
3054
3055         //XXX Why do we unlock here ?
3056         // uncomment it for now, till my setup with debug_threads and detect_deadlocks starts to complain
3057         //ASTOBJ_UNLOCK(parkinglot);
3058
3059         if (peer) {
3060                 /* Play a courtesy to the source(s) configured to prefix the bridge connecting */
3061                 
3062                 if (!ast_strlen_zero(courtesytone)) {
3063                         int error = 0;
3064                         ast_indicate(peer, AST_CONTROL_UNHOLD);
3065                         if (parkedplay == 0) {
3066                                 error = ast_stream_and_wait(chan, courtesytone, "");
3067                         } else if (parkedplay == 1) {
3068                                 error = ast_stream_and_wait(peer, courtesytone, "");
3069                         } else if (parkedplay == 2) {
3070                                 if (!ast_streamfile(chan, courtesytone, chan->language) &&
3071                                                 !ast_streamfile(peer, courtesytone, chan->language)) {
3072                                         /*! \todo XXX we would like to wait on both! */
3073                                         res = ast_waitstream(chan, "");
3074                                         if (res >= 0)
3075                                                 res = ast_waitstream(peer, "");
3076                                         if (res < 0)
3077                                                 error = 1;
3078                                 }
3079                         }
3080                         if (error) {
3081                                 ast_log(LOG_WARNING, "Failed to play courtesy tone!\n");
3082                                 ast_hangup(peer);
3083                                 return -1;
3084                         }
3085                 } else
3086                         ast_indicate(peer, AST_CONTROL_UNHOLD); 
3087
3088                 res = ast_channel_make_compatible(chan, peer);
3089                 if (res < 0) {
3090                         ast_log(LOG_WARNING, "Could not make channels %s and %s compatible for bridge\n", chan->name, peer->name);
3091                         ast_hangup(peer);
3092                         return -1;
3093                 }
3094                 /* This runs sorta backwards, since we give the incoming channel control, as if it
3095                    were the person called. */
3096                 ast_verb(3, "Channel %s connected to parked call %d\n", chan->name, park);
3097
3098                 pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
3099                 ast_cdr_setdestchan(chan->cdr, peer->name);
3100                 memset(&config, 0, sizeof(struct ast_bridge_config));
3101                 if ((parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH))
3102                         ast_set_flag(&(config.features_callee), AST_FEATURE_REDIRECT);
3103                 if ((parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcalltransfers == AST_FEATURE_FLAG_BYBOTH))
3104                         ast_set_flag(&(config.features_caller), AST_FEATURE_REDIRECT);
3105                 if ((parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYCALLEE) || (parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYBOTH))
3106                         ast_set_flag(&(config.features_callee), AST_FEATURE_PARKCALL);
3107                 if ((parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYCALLER) || (parkinglot->parkedcallreparking == AST_FEATURE_FLAG_BYBOTH))
3108                         ast_set_flag(&(config.features_caller), AST_FEATURE_PARKCALL);
3109                 res = ast_bridge_call(chan, peer, &config);
3110
3111                 pbx_builtin_setvar_helper(chan, "PARKEDCHANNEL", peer->name);
3112                 ast_cdr_setdestchan(chan->cdr, peer->name);
3113
3114                 /* Simulate the PBX hanging up */
3115                 ast_hangup(peer);
3116                 return res;
3117         } else {
3118                 /*! \todo XXX Play a message XXX */
3119                 if (ast_stream_and_wait(chan, "pbx-invalidpark", ""))
3120                         ast_log(LOG_WARNING, "ast_streamfile of %s failed on %s\n", "pbx-invalidpark", chan->name);
3121                 ast_verb(3, "Channel %s tried to talk to nonexistent parked call %d\n", chan->name, park);
3122                 res = -1;
3123         }
3124
3125         return res;
3126 }
3127
3128 static int park_exec(struct ast_channel *chan, void *data) 
3129 {
3130         return park_exec_full(chan, data, default_parkinglot);
3131 }
3132
3133 /*! \brief Unreference parkinglot object. If no more references,
3134         then go ahead and delete it */
3135 static void parkinglot_unref(struct ast_parkinglot *parkinglot) 
3136 {
3137         int refcount = ao2_ref(parkinglot, -1);
3138         if (option_debug > 2)
3139                 ast_log(LOG_DEBUG, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount - 1);
3140 }
3141
3142 static struct ast_parkinglot *parkinglot_addref(struct ast_parkinglot *parkinglot)
3143 {
3144         int refcount = ao2_ref(parkinglot, +1);
3145         if (option_debug > 2)
3146                 ast_log(LOG_DEBUG, "Multiparking: %s refcount now %d\n", parkinglot->name, refcount + 1);
3147         return parkinglot;
3148 }
3149
3150 /*! \brief Allocate parking lot structure */
3151 static struct ast_parkinglot *create_parkinglot(char *name)
3152 {
3153         struct ast_parkinglot *newlot = (struct ast_parkinglot *) NULL;
3154
3155         if (!name)
3156                 return NULL;
3157
3158         newlot = ao2_alloc(sizeof(*newlot), parkinglot_destroy);
3159         if (!newlot)
3160                 return NULL;
3161         
3162         ast_copy_string(newlot->name, name, sizeof(newlot->name));
3163
3164         return newlot;
3165 }
3166
3167 /*! \brief Destroy a parking lot */
3168 static void parkinglot_destroy(void *obj)
3169 {
3170         struct ast_parkinglot *ruin = obj;
3171         struct ast_context *con;
3172         con = ast_context_find(ruin->parking_con);
3173         if (con)
3174                 ast_context_destroy(con, registrar);
3175         ao2_unlink(parkinglots, ruin);
3176 }
3177
3178 /*! \brief Build parkinglot from configuration and chain it in */
3179 static struct ast_parkinglot *build_parkinglot(char *name, struct ast_variable *var)
3180 {
3181         struct ast_parkinglot *parkinglot;
3182         struct ast_context *con = NULL;
3183
3184         struct ast_variable *confvar = var;
3185         int error = 0;
3186         int start = 0, end = 0;
3187         int oldparkinglot = 0;
3188
3189         parkinglot = find_parkinglot(name);
3190         if (parkinglot)
3191                 oldparkinglot = 1;
3192         else
3193                 parkinglot = create_parkinglot(name);
3194
3195         if (!parkinglot)
3196                 return NULL;
3197
3198         ao2_lock(parkinglot);
3199
3200         if (option_debug)
3201                 ast_log(LOG_DEBUG, "Building parking lot %s\n", name);
3202         
3203         /* Do some config stuff */
3204         while(confvar) {
3205                 if (!strcasecmp(confvar->name, "context")) {
3206                         ast_copy_string(parkinglot->parking_con, confvar->value, sizeof(parkinglot->parking_con));
3207                 } else if (!strcasecmp(confvar->name, "parkingtime")) {
3208                         if ((sscanf(confvar->value, "%d", &parkinglot->parkingtime) != 1) || (parkinglot->parkingtime < 1)) {
3209                                 ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", confvar->value);
3210                                 parkinglot->parkingtime = DEFAULT_PARK_TIME;
3211                         } else
3212                                 parkinglot->parkingtime = parkinglot->parkingtime * 1000;
3213                 } else if (!strcasecmp(confvar->name, "parkpos")) {
3214                         if (sscanf(confvar->value, "%d-%d", &start, &end) != 2) {
3215                                 ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers at line %d of parking.conf\n", confvar->lineno);
3216                                 error = 1;
3217                         } else {
3218                                 parkinglot->parking_start = start;
3219                                 parkinglot->parking_stop = end;
3220                         }
3221                 } else if (!strcasecmp(confvar->name, "findslot")) {
3222                         parkinglot->parkfindnext = (!strcasecmp(confvar->value, "next"));
3223                 }
3224                 confvar = confvar->next;
3225         }
3226         /* make sure parkingtime is set if not specified */
3227         if (parkinglot->parkingtime == 0) {
3228                 parkinglot->parkingtime = DEFAULT_PARK_TIME;
3229         }
3230
3231         if (!var) {     /* Default parking lot */
3232                 ast_copy_string(parkinglot->parking_con, "parkedcalls", sizeof(parkinglot->parking_con));
3233                 ast_copy_string(parkinglot->parking_con_dial, "park-dial", sizeof(parkinglot->parking_con_dial));
3234                 ast_copy_string(parkinglot->mohclass, "default", sizeof(parkinglot->mohclass));
3235         }
3236
3237         /* Check for errors */
3238         if (ast_strlen_zero(parkinglot->parking_con)) {
3239                 ast_log(LOG_WARNING, "Parking lot %s lacks context\n", name);
3240                 error = 1;
3241         }
3242
3243         /* Create context */
3244         if (!error && !(con = ast_context_find_or_create(NULL, NULL, parkinglot->parking_con, registrar))) {
3245                 ast_log(LOG_ERROR, "Parking context '%s' does not exist and unable to create\n", parkinglot->parking_con);
3246                 error = 1;
3247         }
3248
3249         /* Add a parking extension into the context */
3250         if (!oldparkinglot) {
3251                 if (!ast_strlen_zero(ast_parking_ext())) {
3252                         if (ast_add_extension2(con, 1, ast_parking_ext(), 1, NULL, NULL, parkcall, strdup(""), ast_free, registrar) == -1)
3253                                 error = 1;
3254                 }
3255         }
3256
3257         ao2_unlock(parkinglot);
3258
3259         if (error) {
3260                 ast_log(LOG_WARNING, "Parking %s not open for business. Configuration error.\n", name);
3261                 parkinglot_destroy(parkinglot);
3262                 return NULL;
3263         }
3264         if (option_debug)
3265                 ast_log(LOG_DEBUG, "Parking %s now open for business. (start exten %d end %d)\n", name, start, end);
3266
3267
3268         /* Move it into the list, if it wasn't already there */
3269         if (!oldparkinglot) {
3270                 ao2_link(parkinglots, parkinglot);
3271         }
3272         parkinglot_unref(parkinglot);
3273
3274         return parkinglot;
3275 }
3276
3277
3278 /*! 
3279  * \brief Add parking hints for all defined parking lots 
3280  * \param context
3281  * \param start starting parkinglot number
3282  * \param stop ending parkinglot number
3283 */
3284 static void park_add_hints(char *context, int start, int stop)
3285 {
3286         int numext;
3287         char device[AST_MAX_EXTENSION];
3288         char exten[10];
3289
3290         for (numext = start; numext <= stop; numext++) {
3291                 snprintf(exten, sizeof(exten), "%d", numext);
3292                 snprintf(device, sizeof(device), "park:%s@%s", exten, context);
3293                 ast_add_extension(context, 1, exten, PRIORITY_HINT, NULL, NULL, device, NULL, NULL, registrar);
3294         }
3295 }
3296
3297 static int load_config(void) 
3298 {
3299         int start = 0, end = 0;
3300         int res;
3301         int i;
3302         struct ast_context *con = NULL;
3303         struct ast_config *cfg = NULL;
3304         struct ast_variable *var = NULL;
3305         struct feature_group *fg = NULL;
3306         struct ast_flags config_flags = { 0 };
3307         char old_parking_ext[AST_MAX_EXTENSION];
3308         char old_parking_con[AST_MAX_EXTENSION] = "";
3309         char *ctg; 
3310         static const char *categories[] = { 
3311                 /* Categories in features.conf that are not
3312                  * to be parsed as group categories
3313                  */
3314                 "general",
3315                 "featuremap",
3316                 "applicationmap"
3317         };
3318
3319         if (default_parkinglot) {
3320                 strcpy(old_parking_con, default_parkinglot->parking_con);
3321                 strcpy(old_parking_ext, parking_ext);
3322         } else {
3323                 default_parkinglot = build_parkinglot(DEFAULT_PARKINGLOT, NULL);
3324                 if (default_parkinglot) {
3325                         ao2_lock(default_parkinglot);
3326                         default_parkinglot->parking_start = 701;
3327                         default_parkinglot->parking_stop = 750;
3328                         default_parkinglot->parking_offset = 0;
3329                         default_parkinglot->parkfindnext = 0;
3330                         default_parkinglot->parkingtime = DEFAULT_PARK_TIME;
3331                         ao2_unlock(default_parkinglot);
3332                 }
3333         }
3334         if (default_parkinglot) {
3335                 if (option_debug)
3336                         ast_log(LOG_DEBUG, "Configuration of default parkinglot done.\n");
3337         } else {
3338                 ast_log(LOG_ERROR, "Configuration of default parkinglot failed.\n");
3339                 return -1;
3340         }
3341         
3342
3343         /* Reset to defaults */
3344         strcpy(parking_ext, "700");
3345         strcpy(pickup_ext, "*8");
3346         courtesytone[0] = '\0';
3347         strcpy(xfersound, "beep");
3348         strcpy(xferfailsound, "pbx-invalid");
3349         adsipark = 0;
3350         comebacktoorigin = 1;
3351
3352         default_parkinglot->parkaddhints = 0;
3353         default_parkinglot->parkedcalltransfers = 0;
3354         default_parkinglot->parkedcallreparking = 0;
3355
3356         transferdigittimeout = DEFAULT_TRANSFER_DIGIT_TIMEOUT;
3357         featuredigittimeout = DEFAULT_FEATURE_DIGIT_TIMEOUT;
3358         atxfernoanswertimeout = DEFAULT_NOANSWER_TIMEOUT_ATTENDED_TRANSFER;
3359         atxferloopdelay = DEFAULT_ATXFER_LOOP_DELAY;
3360         atxferdropcall = DEFAULT_ATXFER_DROP_CALL;
3361         atxfercallbackretries = DEFAULT_ATXFER_CALLBACK_RETRIES;
3362
3363         cfg = ast_config_load2("features.conf", "features", config_flags);
3364         if (cfg == CONFIG_STATUS_FILEMISSING || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
3365                 ast_log(LOG_WARNING,"Could not load features.conf\n");
3366                 return 0;
3367         }
3368         for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
3369                 if (!strcasecmp(var->name, "parkext")) {
3370                         ast_copy_string(parking_ext, var->value, sizeof(parking_ext));
3371                 } else if (!strcasecmp(var->name, "context")) {
3372                         ast_copy_string(default_parkinglot->parking_con, var->value, sizeof(default_parkinglot->parking_con));
3373                 } else if (!strcasecmp(var->name, "parkingtime")) {
3374                         if ((sscanf(var->value, "%d", &default_parkinglot->parkingtime) != 1) || (default_parkinglot->parkingtime < 1)) {
3375                                 ast_log(LOG_WARNING, "%s is not a valid parkingtime\n", var->value);
3376                                 default_parkinglot->parkingtime = DEFAULT_PARK_TIME;
3377                         } else
3378                                 default_parkinglot->parkingtime = default_parkinglot->parkingtime * 1000;
3379                 } else if (!strcasecmp(var->name, "parkpos")) {
3380                         if (sscanf(var->value, "%d-%d", &start, &end) != 2) {
3381                                 ast_log(LOG_WARNING, "Format for parking positions is a-b, where a and b are numbers at line %d of features.conf\n", var->lineno);
3382                         } else if (default_parkinglot) {
3383                                 default_parkinglot->parking_start = start;
3384                                 default_parkinglot->parking_stop = end;
3385                         } else {
3386                                 ast_log(LOG_WARNING, "No default parking lot!\n");
3387                         }
3388                 } else if (!strcasecmp(var->name, "findslot")) {
3389                         default_parkinglot->parkfindnext = (!strcasecmp(var->value, "next"));
3390                 } else if (!strcasecmp(var->name, "parkinghints")) {
3391                         default_parkinglot->parkaddhints = ast_true(var->value);
3392                 } else if (!strcasecmp(var->name, "parkedcalltransfers")) {
3393                         if (!strcasecmp(var->value, "both"))
3394                                 default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYBOTH;
3395                         else if (!strcasecmp(var->value, "caller"))
3396                                 default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLER;
3397                         else if (!strcasecmp(var->value, "callee"))
3398                                 default_parkinglot->parkedcalltransfers = AST_FEATURE_FLAG_BYCALLEE;
3399                 } else if (!strcasecmp(var->name, "parkedcallreparking")) {
3400                         if (!strcasecmp(var->value, "both"))