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