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