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