use Set instead of SetVar in the sample so that we don't get warnings when
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <sys/time.h>
18 #include <signal.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <math.h>                       /* For PI */
22
23 #ifdef ZAPTEL_OPTIMIZATIONS
24 #include <sys/ioctl.h>
25 #ifdef __linux__
26 #include <linux/zaptel.h>
27 #else
28 #include <zaptel.h>
29 #endif /* __linux__ */
30 #ifndef ZT_TIMERPING
31 #error "You need newer zaptel!  Please cvs update zaptel"
32 #endif
33 #endif
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include "asterisk/pbx.h"
40 #include "asterisk/frame.h"
41 #include "asterisk/sched.h"
42 #include "asterisk/options.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/musiconhold.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/say.h"
47 #include "asterisk/file.h"
48 #include "asterisk/cli.h"
49 #include "asterisk/translate.h"
50 #include "asterisk/manager.h"
51 #include "asterisk/chanvars.h"
52 #include "asterisk/linkedlists.h"
53 #include "asterisk/indications.h"
54 #include "asterisk/monitor.h"
55 #include "asterisk/causes.h"
56 #include "asterisk/callerid.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/lock.h"
59 #include "asterisk/app.h"
60 #include "asterisk/transcap.h"
61 #include "asterisk/devicestate.h"
62
63 /* uncomment if you have problems with 'monitoring' synchronized files */
64 #if 0
65 #define MONITOR_CONSTANT_DELAY
66 #define MONITOR_DELAY   150 * 8         /* 150 ms of MONITORING DELAY */
67 #endif
68
69 /*
70  * Prevent new channel allocation if shutting down.
71  */
72 static int shutting_down = 0;
73
74 static int uniqueint = 0;
75
76 unsigned long global_fin = 0, global_fout = 0;
77
78 /* XXX Lock appropriately in more functions XXX */
79
80 struct chanlist {
81         const struct ast_channel_tech *tech;
82         struct chanlist *next;
83 };
84
85 static struct chanlist *backends = NULL;
86
87 /*
88  * the list of channels we have
89  */
90 static struct ast_channel *channels = NULL;
91
92 /* Protect the channel list, both backends and channels.
93  */
94 AST_MUTEX_DEFINE_STATIC(chlock);
95
96 const struct ast_cause {
97         int cause;
98         const char *desc;
99 } causes[] = {
100         { AST_CAUSE_UNALLOCATED, "Unallocated (unassigned) number" },
101         { AST_CAUSE_NO_ROUTE_TRANSIT_NET, "No route to specified transmit network" },
102         { AST_CAUSE_NO_ROUTE_DESTINATION, "No route to destination" },
103         { AST_CAUSE_CHANNEL_UNACCEPTABLE, "Channel unacceptable" },
104         { AST_CAUSE_CALL_AWARDED_DELIVERED, "Call awarded and being delivered in an established channel" },
105         { AST_CAUSE_NORMAL_CLEARING, "Normal Clearing" },
106         { AST_CAUSE_USER_BUSY, "User busy" },
107         { AST_CAUSE_NO_USER_RESPONSE, "No user responding" },
108         { AST_CAUSE_NO_ANSWER, "User alerting, no answer" },
109         { AST_CAUSE_CALL_REJECTED, "Call Rejected" },
110         { AST_CAUSE_NUMBER_CHANGED, "Number changed" },
111         { AST_CAUSE_DESTINATION_OUT_OF_ORDER, "Destination out of order" },
112         { AST_CAUSE_INVALID_NUMBER_FORMAT, "Invalid number format" },
113         { AST_CAUSE_FACILITY_REJECTED, "Facility rejected" },
114         { AST_CAUSE_RESPONSE_TO_STATUS_ENQUIRY, "Response to STATus ENQuiry" },
115         { AST_CAUSE_NORMAL_UNSPECIFIED, "Normal, unspecified" },
116         { AST_CAUSE_NORMAL_CIRCUIT_CONGESTION, "Circuit/channel congestion" },
117         { AST_CAUSE_NETWORK_OUT_OF_ORDER, "Network out of order" },
118         { AST_CAUSE_NORMAL_TEMPORARY_FAILURE, "Temporary failure" },
119         { AST_CAUSE_SWITCH_CONGESTION, "Switching equipment congestion" },
120         { AST_CAUSE_ACCESS_INFO_DISCARDED, "Access information discarded" },
121         { AST_CAUSE_REQUESTED_CHAN_UNAVAIL, "Requested channel not available" },
122         { AST_CAUSE_PRE_EMPTED, "Pre-empted" },
123         { AST_CAUSE_FACILITY_NOT_SUBSCRIBED, "Facility not subscribed" },
124         { AST_CAUSE_OUTGOING_CALL_BARRED, "Outgoing call barred" },
125         { AST_CAUSE_INCOMING_CALL_BARRED, "Incoming call barred" },
126         { AST_CAUSE_BEARERCAPABILITY_NOTAUTH, "Bearer capability not authorized" },
127         { AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, "Bearer capability not available" },
128         { AST_CAUSE_BEARERCAPABILITY_NOTIMPL, "Bearer capability not implemented" },
129         { AST_CAUSE_CHAN_NOT_IMPLEMENTED, "Channel not implemented" },
130         { AST_CAUSE_FACILITY_NOT_IMPLEMENTED, "Facility not implemented" },
131         { AST_CAUSE_INVALID_CALL_REFERENCE, "Invalid call reference value" },
132         { AST_CAUSE_INCOMPATIBLE_DESTINATION, "Incompatible destination" },
133         { AST_CAUSE_INVALID_MSG_UNSPECIFIED, "Invalid message unspecified" },
134         { AST_CAUSE_MANDATORY_IE_MISSING, "Mandatory information element is missing" },
135         { AST_CAUSE_MESSAGE_TYPE_NONEXIST, "Message type nonexist." },
136         { AST_CAUSE_WRONG_MESSAGE, "Wrong message" },
137         { AST_CAUSE_IE_NONEXIST, "Info. element nonexist or not implemented" },
138         { AST_CAUSE_INVALID_IE_CONTENTS, "Invalid information element contents" },
139         { AST_CAUSE_WRONG_CALL_STATE, "Message not compatible with call state" },
140         { AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, "Recover on timer expiry" },
141         { AST_CAUSE_MANDATORY_IE_LENGTH_ERROR, "Mandatory IE length error" },
142         { AST_CAUSE_PROTOCOL_ERROR, "Protocol error, unspecified" },
143         { AST_CAUSE_INTERWORKING, "Interworking, unspecified" },
144 };
145
146
147 static int show_channeltypes(int fd, int argc, char *argv[])
148 {
149 #define FORMAT  "%-10.10s  %-30.30s %-12.12s %-12.12s %-12.12s\n"
150         struct chanlist *cl = backends;
151         ast_cli(fd, FORMAT, "Type", "Description",       "Devicestate", "Indications", "Transfer");
152         ast_cli(fd, FORMAT, "----------", "-----------", "-----------", "-----------", "--------");
153         if (ast_mutex_lock(&chlock)) {
154                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
155                 return -1;
156         }
157         while (cl) {
158                 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description, 
159                         (cl->tech->devicestate) ? "yes" : "no", 
160                         (cl->tech->indicate) ? "yes" : "no",
161                         (cl->tech->transfer) ? "yes" : "no");
162                 cl = cl->next;
163         }
164         ast_mutex_unlock(&chlock);
165         return RESULT_SUCCESS;
166
167 #undef FORMAT
168
169 }
170
171 static char show_channeltypes_usage[] = 
172 "Usage: show channeltypes\n"
173 "       Shows available channel types registered in your Asterisk server.\n";
174
175 static struct ast_cli_entry cli_show_channeltypes = 
176         { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
177
178 /*--- ast_check_hangup: Checks to see if a channel is needing hang up */
179 int ast_check_hangup(struct ast_channel *chan)
180 {
181         time_t  myt;
182
183         /* if soft hangup flag, return true */
184         if (chan->_softhangup) 
185                 return 1;
186         /* if no technology private data, return true */
187         if (!chan->tech_pvt) 
188                 return 1;
189         /* if no hangup scheduled, just return here */
190         if (!chan->whentohangup) 
191                 return 0;
192         time(&myt); /* get current time */
193         /* return, if not yet */
194         if (chan->whentohangup > myt) 
195                 return 0;
196         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
197         return 1;
198 }
199
200 static int ast_check_hangup_locked(struct ast_channel *chan)
201 {
202         int res;
203         ast_mutex_lock(&chan->lock);
204         res = ast_check_hangup(chan);
205         ast_mutex_unlock(&chan->lock);
206         return res;
207 }
208
209 /*--- ast_begin_shutdown: Initiate system shutdown */
210 void ast_begin_shutdown(int hangup)
211 {
212         struct ast_channel *c;
213         shutting_down = 1;
214         if (hangup) {
215                 ast_mutex_lock(&chlock);
216                 c = channels;
217                 while(c) {
218                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
219                         c = c->next;
220                 }
221                 ast_mutex_unlock(&chlock);
222         }
223 }
224
225 /*--- ast_active_channels: returns number of active/allocated channels */
226 int ast_active_channels(void)
227 {
228         struct ast_channel *c;
229         int cnt = 0;
230         ast_mutex_lock(&chlock);
231         c = channels;
232         while(c) {
233                 cnt++;
234                 c = c->next;
235         }
236         ast_mutex_unlock(&chlock);
237         return cnt;
238 }
239
240 /*--- ast_cancel_shutdown: Cancel a shutdown in progress */
241 void ast_cancel_shutdown(void)
242 {
243         shutting_down = 0;
244 }
245
246 /*--- ast_shutting_down: Returns non-zero if Asterisk is being shut down */
247 int ast_shutting_down(void)
248 {
249         return shutting_down;
250 }
251
252 /*--- ast_channel_setwhentohangup: Set when to hangup channel */
253 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
254 {
255         time_t  myt;
256
257         time(&myt);
258         if (offset)
259                 chan->whentohangup = myt + offset;
260         else
261                 chan->whentohangup = 0;
262         return;
263 }
264
265 /*--- ast_channel_register: Register a new telephony channel in Asterisk */
266 int ast_channel_register(const struct ast_channel_tech *tech)
267 {
268         struct chanlist *chan;
269
270         ast_mutex_lock(&chlock);
271
272         chan = backends;
273         while (chan) {
274                 if (!strcasecmp(tech->type, chan->tech->type)) {
275                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
276                         ast_mutex_unlock(&chlock);
277                         return -1;
278                 }
279                 chan = chan->next;
280         }
281
282         chan = malloc(sizeof(*chan));
283         if (!chan) {
284                 ast_log(LOG_WARNING, "Out of memory\n");
285                 ast_mutex_unlock(&chlock);
286                 return -1;
287         }
288         chan->tech = tech;
289         chan->next = backends;
290         backends = chan;
291
292         if (option_debug)
293                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
294
295         if (option_verbose > 1)
296                 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
297                             chan->tech->description);
298
299         ast_mutex_unlock(&chlock);
300         return 0;
301 }
302
303 void ast_channel_unregister(const struct ast_channel_tech *tech)
304 {
305         struct chanlist *chan, *last=NULL;
306
307         if (option_debug)
308                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
309
310         ast_mutex_lock(&chlock);
311
312         chan = backends;
313         while (chan) {
314                 if (chan->tech == tech) {
315                         if (last)
316                                 last->next = chan->next;
317                         else
318                                 backends = backends->next;
319                         free(chan);
320                         ast_mutex_unlock(&chlock);
321
322                         if (option_verbose > 1)
323                                 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
324
325                         return;
326                 }
327                 last = chan;
328                 chan = chan->next;
329         }
330
331         ast_mutex_unlock(&chlock);
332 }
333
334 const struct ast_channel_tech *ast_get_channel_tech(const char *name)
335 {
336         struct chanlist *chanls;
337
338         if (ast_mutex_lock(&chlock)) {
339                 ast_log(LOG_WARNING, "Unable to lock channel tech list\n");
340                 return NULL;
341         }
342
343         for (chanls = backends; chanls; chanls = chanls->next) {
344                 if (strcasecmp(name, chanls->tech->type))
345                         continue;
346
347                 ast_mutex_unlock(&chlock);
348                 return chanls->tech;
349         }
350
351         ast_mutex_unlock(&chlock);
352         return NULL;
353 }
354
355 /*--- ast_cause2str: Gives the string form of a given hangup cause */
356 const char *ast_cause2str(int cause)
357 {
358         int x;
359
360         for (x=0; x < sizeof(causes) / sizeof(causes[0]); x++) 
361                 if (causes[x].cause == cause)
362                         return causes[x].desc;
363
364         return "Unknown";
365 }
366
367 /*--- ast_state2str: Gives the string form of a given channel state */
368 char *ast_state2str(int state)
369 {
370         /* XXX Not reentrant XXX */
371         static char localtmp[256];
372         switch(state) {
373         case AST_STATE_DOWN:
374                 return "Down";
375         case AST_STATE_RESERVED:
376                 return "Rsrvd";
377         case AST_STATE_OFFHOOK:
378                 return "OffHook";
379         case AST_STATE_DIALING:
380                 return "Dialing";
381         case AST_STATE_RING:
382                 return "Ring";
383         case AST_STATE_RINGING:
384                 return "Ringing";
385         case AST_STATE_UP:
386                 return "Up";
387         case AST_STATE_BUSY:
388                 return "Busy";
389         default:
390                 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
391                 return localtmp;
392         }
393 }
394
395 /*--- ast_transfercapability2str: Gives the string form of a given transfer capability */
396 char *ast_transfercapability2str(int transfercapability)
397 {
398         switch(transfercapability) {
399         case AST_TRANS_CAP_SPEECH:
400                 return "SPEECH";
401         case AST_TRANS_CAP_DIGITAL:
402                 return "DIGITAL";
403         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
404                 return "RESTRICTED_DIGITAL";
405         case AST_TRANS_CAP_3_1K_AUDIO:
406                 return "3K1AUDIO";
407         case AST_TRANS_CAP_DIGITAL_W_TONES:
408                 return "DIGITAL_W_TONES";
409         case AST_TRANS_CAP_VIDEO:
410                 return "VIDEO";
411         default:
412                 return "UNKNOWN";
413         }
414 }
415
416 /*--- ast_best_codec: Pick the best codec */
417 int ast_best_codec(int fmts)
418 {
419         /* This just our opinion, expressed in code.  We are asked to choose
420            the best codec to use, given no information */
421         int x;
422         static int prefs[] = 
423         {
424                 /* Okay, ulaw is used by all telephony equipment, so start with it */
425                 AST_FORMAT_ULAW,
426                 /* Unless of course, you're a silly European, so then prefer ALAW */
427                 AST_FORMAT_ALAW,
428                 /* Okay, well, signed linear is easy to translate into other stuff */
429                 AST_FORMAT_SLINEAR,
430                 /* G.726 is standard ADPCM */
431                 AST_FORMAT_G726,
432                 /* ADPCM has great sound quality and is still pretty easy to translate */
433                 AST_FORMAT_ADPCM,
434                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
435                    translate and sounds pretty good */
436                 AST_FORMAT_GSM,
437                 /* iLBC is not too bad */
438                 AST_FORMAT_ILBC,
439                 /* Speex is free, but computationally more expensive than GSM */
440                 AST_FORMAT_SPEEX,
441                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
442                    to use it */
443                 AST_FORMAT_LPC10,
444                 /* G.729a is faster than 723 and slightly less expensive */
445                 AST_FORMAT_G729A,
446                 /* Down to G.723.1 which is proprietary but at least designed for voice */
447                 AST_FORMAT_G723_1,
448         };
449         
450         
451         /* Find the first prefered codec in the format given */
452         for (x=0; x < (sizeof(prefs) / sizeof(prefs[0]) ); x++)
453                 if (fmts & prefs[x])
454                         return prefs[x];
455         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
456         return 0;
457 }
458
459 static const struct ast_channel_tech null_tech = {
460         .type = "NULL",
461         .description = "Null channel (should not see this)",
462 };
463
464 /*--- ast_channel_alloc: Create a new channel structure */
465 struct ast_channel *ast_channel_alloc(int needqueue)
466 {
467         struct ast_channel *tmp;
468         int x;
469         int flags;
470         struct varshead *headp;        
471                 
472
473         /* If shutting down, don't allocate any new channels */
474         if (shutting_down) {
475                 ast_log(LOG_WARNING, "Channel allocation failed: Refusing due to active shutdown\n");
476                 return NULL;
477         }
478
479         tmp = malloc(sizeof(struct ast_channel));
480         if (!tmp) {
481                 ast_log(LOG_WARNING, "Channel allocation failed: Out of memory\n");
482                 return NULL;
483         }
484
485         memset(tmp, 0, sizeof(struct ast_channel));
486         tmp->sched = sched_context_create();
487         if (!tmp->sched) {
488                 ast_log(LOG_WARNING, "Channel allocation failed: Unable to create schedule context\n");
489                 free(tmp);
490                 return NULL;
491         }
492         
493         for (x=0; x<AST_MAX_FDS - 1; x++)
494                 tmp->fds[x] = -1;
495
496 #ifdef ZAPTEL_OPTIMIZATIONS
497         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
498         if (tmp->timingfd > -1) {
499                 /* Check if timing interface supports new
500                    ping/pong scheme */
501                 flags = 1;
502                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
503                         needqueue = 0;
504         }
505 #else
506         tmp->timingfd = -1;                                     
507 #endif                                  
508
509         if (needqueue) {
510                 if (pipe(tmp->alertpipe)) {
511                         ast_log(LOG_WARNING, "Channel allocation failed: Can't create alert pipe!\n");
512                         free(tmp);
513                         return NULL;
514                 } else {
515                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
516                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
517                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
518                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
519                 }
520         } else 
521                 /* Make sure we've got it done right if they don't */
522                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
523
524         /* Always watch the alertpipe */
525         tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
526         /* And timing pipe */
527         tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
528         strcpy(tmp->name, "**Unkown**");
529         /* Initial state */
530         tmp->_state = AST_STATE_DOWN;
531         tmp->streamid = -1;
532         tmp->appl = NULL;
533         tmp->data = NULL;
534         tmp->fin = global_fin;
535         tmp->fout = global_fout;
536         snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long) time(NULL), uniqueint++);
537         headp = &tmp->varshead;
538         ast_mutex_init(&tmp->lock);
539         AST_LIST_HEAD_INIT(headp);
540         strcpy(tmp->context, "default");
541         ast_copy_string(tmp->language, defaultlanguage, sizeof(tmp->language));
542         strcpy(tmp->exten, "s");
543         tmp->priority = 1;
544         tmp->amaflags = ast_default_amaflags;
545         ast_copy_string(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode));
546
547         tmp->tech = &null_tech;
548
549         ast_mutex_lock(&chlock);
550         tmp->next = channels;
551         channels = tmp;
552
553         ast_mutex_unlock(&chlock);
554         return tmp;
555 }
556
557 /*--- ast_queue_frame: Queue an outgoing media frame */
558 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
559 {
560         struct ast_frame *f;
561         struct ast_frame *prev, *cur;
562         int blah = 1;
563         int qlen = 0;
564
565         /* Build us a copy and free the original one */
566         f = ast_frdup(fin);
567         if (!f) {
568                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
569                 return -1;
570         }
571         ast_mutex_lock(&chan->lock);
572         prev = NULL;
573         cur = chan->readq;
574         while(cur) {
575                 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
576                         /* Don't bother actually queueing anything after a hangup */
577                         ast_frfree(f);
578                         ast_mutex_unlock(&chan->lock);
579                         return 0;
580                 }
581                 prev = cur;
582                 cur = cur->next;
583                 qlen++;
584         }
585         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
586         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
587                 if (fin->frametype != AST_FRAME_VOICE) {
588                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
589                         CRASH;
590                 } else {
591                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
592                         ast_frfree(f);
593                         ast_mutex_unlock(&chan->lock);
594                         return 0;
595                 }
596         }
597         if (prev)
598                 prev->next = f;
599         else
600                 chan->readq = f;
601         if (chan->alertpipe[1] > -1) {
602                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
603                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
604                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
605 #ifdef ZAPTEL_OPTIMIZATIONS
606         } else if (chan->timingfd > -1) {
607                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
608 #endif                          
609         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
610                 pthread_kill(chan->blocker, SIGURG);
611         }
612         ast_mutex_unlock(&chan->lock);
613         return 0;
614 }
615
616 /*--- ast_queue_hangup: Queue a hangup frame for channel */
617 int ast_queue_hangup(struct ast_channel *chan)
618 {
619         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
620         chan->_softhangup |= AST_SOFTHANGUP_DEV;
621         return ast_queue_frame(chan, &f);
622 }
623
624 /*--- ast_queue_control: Queue a control frame */
625 int ast_queue_control(struct ast_channel *chan, int control)
626 {
627         struct ast_frame f = { AST_FRAME_CONTROL, };
628         f.subclass = control;
629         return ast_queue_frame(chan, &f);
630 }
631
632 /*--- ast_channel_defer_dtmf: Set defer DTMF flag on channel */
633 int ast_channel_defer_dtmf(struct ast_channel *chan)
634 {
635         int pre = 0;
636
637         if (chan) {
638                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
639                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
640         }
641         return pre;
642 }
643
644 /*--- ast_channel_undefer_dtmf: Unset defer DTMF flag on channel */
645 void ast_channel_undefer_dtmf(struct ast_channel *chan)
646 {
647         if (chan)
648                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
649 }
650
651 /*
652  * Helper function to return the channel after prev, or the one matching name,
653  * with the channel's lock held. If getting the individual lock fails,
654  * unlock and retry quickly up to 10 times, then give up.
655  * 
656  * XXX Note that this code has cost O(N) because of the need to verify
657  * that the object is still on the global list.
658  *
659  * XXX also note that accessing fields (e.g. c->name in ast_log())
660  * can only be done with the lock held or someone could delete the
661  * object while we work on it. This causes some ugliness in the code.
662  * Note that removing the first ast_log() may be harmful, as it would
663  * shorten the retry period and possibly cause failures.
664  * We should definitely go for a better scheme that is deadlock-free.
665  */
666 static struct ast_channel *channel_find_locked(const struct ast_channel *prev,
667                                                const char *name, const int namelen)
668 {
669         const char *msg = prev ? "deadlock" : "initial deadlock";
670         int retries, done;
671         struct ast_channel *c;
672
673         for (retries = 0; retries < 10; retries++) {
674                 ast_mutex_lock(&chlock);
675                 for (c = channels; c; c = c->next) {
676                         if (prev == NULL) {
677                                 /* want head of list */
678                                 if (!name)
679                                         break;
680                                 /* want match by full name */
681                                 if (!namelen) {
682                                         if (!strcasecmp(c->name, name))
683                                                 break;
684                                         else
685                                                 continue;
686                                 }
687                                 /* want match by name prefix */
688                                 if (!strncasecmp(c->name, name, namelen))
689                                         break;
690                         } else if (c == prev) { /* found, return c->next */
691                                 c = c->next;
692                                 break;
693                         }
694                 }
695                 /* exit if chan not found or mutex acquired successfully */
696                 done = (c == NULL) || (ast_mutex_trylock(&c->lock) == 0);
697                 /* this is slightly unsafe, as we _should_ hold the lock to access c->name */
698                 if (!done && c)
699                         ast_log(LOG_DEBUG, "Avoiding %s for '%s'\n", msg, c->name);
700                 ast_mutex_unlock(&chlock);
701                 if (done)
702                         return c;
703                 usleep(1);
704         }
705         /*
706          * c is surely not null, but we don't have the lock so cannot
707          * access c->name
708          */
709         ast_log(LOG_WARNING, "Avoided %s for '%p', %d retries!\n",
710                 msg, c, retries);
711
712         return NULL;
713 }
714
715 /*--- ast_channel_walk_locked: Browse channels in use */
716 struct ast_channel *ast_channel_walk_locked(const struct ast_channel *prev)
717 {
718         return channel_find_locked(prev, NULL, 0);
719 }
720
721 /*--- ast_get_channel_by_name_locked: Get channel by name and lock it */
722 struct ast_channel *ast_get_channel_by_name_locked(const char *name)
723 {
724         return channel_find_locked(NULL, name, 0);
725 }
726
727 /*--- ast_get_channel_by_name_prefix_locked: Get channel by name prefix and lock it */
728 struct ast_channel *ast_get_channel_by_name_prefix_locked(const char *name, const int namelen)
729 {
730         return channel_find_locked(NULL, name, namelen);
731 }
732
733 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
734 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
735         int (*cond)(void*), void *data )
736 {
737         struct ast_frame *f;
738
739         while(ms > 0) {
740                 if( cond && ((*cond)(data) == 0 ) )
741                         return 0;
742                 ms = ast_waitfor(chan, ms);
743                 if (ms <0)
744                         return -1;
745                 if (ms > 0) {
746                         f = ast_read(chan);
747                         if (!f)
748                                 return -1;
749                         ast_frfree(f);
750                 }
751         }
752         return 0;
753 }
754
755 /*--- ast_safe_sleep: Wait, look for hangups */
756 int ast_safe_sleep(struct ast_channel *chan, int ms)
757 {
758         struct ast_frame *f;
759         while(ms > 0) {
760                 ms = ast_waitfor(chan, ms);
761                 if (ms <0)
762                         return -1;
763                 if (ms > 0) {
764                         f = ast_read(chan);
765                         if (!f)
766                                 return -1;
767                         ast_frfree(f);
768                 }
769         }
770         return 0;
771 }
772
773 static void free_cid(struct ast_callerid *cid)
774 {
775         if (cid->cid_dnid)
776                 free(cid->cid_dnid);
777         if (cid->cid_num)
778                 free(cid->cid_num);     
779         if (cid->cid_name)
780                 free(cid->cid_name);    
781         if (cid->cid_ani)
782                 free(cid->cid_ani);
783         if (cid->cid_rdnis)
784                 free(cid->cid_rdnis);
785 }
786
787 /*--- ast_channel_free: Free a channel structure */
788 void ast_channel_free(struct ast_channel *chan)
789 {
790         struct ast_channel *last=NULL, *cur;
791         int fd;
792         struct ast_var_t *vardata;
793         struct ast_frame *f, *fp;
794         struct varshead *headp;
795         char name[AST_CHANNEL_NAME];
796         
797         headp=&chan->varshead;
798         
799         ast_mutex_lock(&chlock);
800         cur = channels;
801         while(cur) {
802                 if (cur == chan) {
803                         if (last)
804                                 last->next = cur->next;
805                         else
806                                 channels = cur->next;
807                         break;
808                 }
809                 last = cur;
810                 cur = cur->next;
811         }
812         if (!cur)
813                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
814         else {
815                 /* Lock and unlock the channel just to be sure nobody
816                    has it locked still */
817                 ast_mutex_lock(&cur->lock);
818                 ast_mutex_unlock(&cur->lock);
819         }
820         if (chan->tech_pvt) {
821                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
822                 free(chan->tech_pvt);
823         }
824
825         ast_copy_string(name, chan->name, sizeof(name));
826         
827         /* Stop monitoring */
828         if (chan->monitor) {
829                 chan->monitor->stop( chan, 0 );
830         }
831
832         /* If there is native format music-on-hold state, free it */
833         if(chan->music_state)
834                 ast_moh_cleanup(chan);
835
836         /* Free translatosr */
837         if (chan->readtrans)
838                 ast_translator_free_path(chan->readtrans);
839         if (chan->writetrans)
840                 ast_translator_free_path(chan->writetrans);
841         if (chan->pbx) 
842                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
843         free_cid(&chan->cid);
844         ast_mutex_destroy(&chan->lock);
845         /* Close pipes if appropriate */
846         if ((fd = chan->alertpipe[0]) > -1)
847                 close(fd);
848         if ((fd = chan->alertpipe[1]) > -1)
849                 close(fd);
850         if ((fd = chan->timingfd) > -1)
851                 close(fd);
852         f = chan->readq;
853         chan->readq = NULL;
854         while(f) {
855                 fp = f;
856                 f = f->next;
857                 ast_frfree(fp);
858         }
859         
860         /* loop over the variables list, freeing all data and deleting list items */
861         /* no need to lock the list, as the channel is already locked */
862         
863         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
864                     vardata = AST_LIST_REMOVE_HEAD(headp, entries);
865                     ast_var_delete(vardata);
866         }
867
868         free(chan);
869         ast_mutex_unlock(&chlock);
870
871         ast_device_state_changed(name);
872 }
873
874 static void ast_spy_detach(struct ast_channel *chan) 
875 {
876         struct ast_channel_spy *chanspy;
877         int to=3000;
878         int sleepms = 100;
879
880         for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
881                 if (chanspy->status == CHANSPY_RUNNING) {
882                         chanspy->status = CHANSPY_DONE;
883                 }
884         }
885
886         /* signal all the spys to get lost and allow them time to unhook themselves 
887            god help us if they don't......
888         */
889         while (chan->spiers && to >= 0) {
890                 ast_safe_sleep(chan, sleepms);
891                 to -= sleepms;
892         }
893         chan->spiers = NULL;
894         return;
895 }
896
897 /*--- ast_softhangup_nolock: Softly hangup a channel, don't lock */
898 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
899 {
900         int res = 0;
901         struct ast_frame f = { AST_FRAME_NULL };
902         if (option_debug)
903                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
904         /* Inform channel driver that we need to be hung up, if it cares */
905         chan->_softhangup |= cause;
906         ast_queue_frame(chan, &f);
907         /* Interrupt any poll call or such */
908         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
909                 pthread_kill(chan->blocker, SIGURG);
910         return res;
911 }
912
913 /*--- ast_softhangup_nolock: Softly hangup a channel, lock */
914 int ast_softhangup(struct ast_channel *chan, int cause)
915 {
916         int res;
917         ast_mutex_lock(&chan->lock);
918         res = ast_softhangup_nolock(chan, cause);
919         ast_mutex_unlock(&chan->lock);
920         return res;
921 }
922
923 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos) 
924 {
925         struct ast_frame *tmpf = NULL;
926         int count = 0;
927
928         ast_mutex_lock(&spy->lock);
929         for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
930                 count++;
931         }
932         if (count > 1000) {
933                 struct ast_frame *freef, *headf;
934
935                 ast_log(LOG_ERROR, "Too many frames queued at once, flushing cache.\n");
936                 headf = spy->queue[pos];
937                 /* deref the queue right away so it looks empty */
938                 spy->queue[pos] = NULL;
939                 tmpf = headf;
940                 /* free the wasted frames */
941                 while (tmpf) {
942                         freef = tmpf;
943                         tmpf = tmpf->next;
944                         ast_frfree(freef);
945                 }
946                 ast_mutex_unlock(&spy->lock);
947                 return;
948         }
949
950         if (tmpf) {
951                 tmpf->next = ast_frdup(f);
952         } else {
953                 spy->queue[pos] = ast_frdup(f);
954         }
955
956         ast_mutex_unlock(&spy->lock);
957 }
958
959 static void free_translation(struct ast_channel *clone)
960 {
961         if (clone->writetrans)
962                 ast_translator_free_path(clone->writetrans);
963         if (clone->readtrans)
964                 ast_translator_free_path(clone->readtrans);
965         clone->writetrans = NULL;
966         clone->readtrans = NULL;
967         clone->rawwriteformat = clone->nativeformats;
968         clone->rawreadformat = clone->nativeformats;
969 }
970
971 /*--- ast_hangup: Hangup a channel */
972 int ast_hangup(struct ast_channel *chan)
973 {
974         int res = 0;
975
976         /* Don't actually hang up a channel that will masquerade as someone else, or
977            if someone is going to masquerade as us */
978         ast_mutex_lock(&chan->lock);
979
980         ast_spy_detach(chan);           /* get rid of spies */
981
982         if (chan->masq) {
983                 if (ast_do_masquerade(chan)) 
984                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
985         }
986
987         if (chan->masq) {
988                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
989                 ast_mutex_unlock(&chan->lock);
990                 return 0;
991         }
992         /* If this channel is one which will be masqueraded into something, 
993            mark it as a zombie already, so we know to free it later */
994         if (chan->masqr) {
995                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
996                 ast_mutex_unlock(&chan->lock);
997                 return 0;
998         }
999         free_translation(chan);
1000         if (chan->stream)               /* Close audio stream */
1001                 ast_closestream(chan->stream);
1002         if (chan->vstream)              /* Close video stream */
1003                 ast_closestream(chan->vstream);
1004         if (chan->sched)
1005                 sched_context_destroy(chan->sched);
1006         
1007         if (chan->generatordata)        /* Clear any tone stuff remaining */ 
1008                 chan->generator->release(chan, chan->generatordata);
1009         chan->generatordata = NULL;
1010         chan->generator = NULL;
1011         if (chan->cdr) {                /* End the CDR if it hasn't already */ 
1012                 ast_cdr_end(chan->cdr);
1013                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */ 
1014         }
1015         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1016                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1017                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1018                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1019                 CRASH;
1020         }
1021         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1022                 if (option_debug)
1023                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1024                 if (chan->tech->hangup)
1025                         res = chan->tech->hangup(chan);
1026         } else {
1027                 if (option_debug)
1028                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1029         }
1030                         
1031         ast_mutex_unlock(&chan->lock);
1032         manager_event(EVENT_FLAG_CALL, "Hangup", 
1033                         "Channel: %s\r\n"
1034                         "Uniqueid: %s\r\n"
1035                         "Cause: %d\r\n"
1036                         "Cause-txt: %s\r\n",
1037                         chan->name, 
1038                         chan->uniqueid, 
1039                         chan->hangupcause,
1040                         ast_cause2str(chan->hangupcause)
1041                         );
1042         ast_channel_free(chan);
1043         return res;
1044 }
1045
1046 int ast_answer(struct ast_channel *chan)
1047 {
1048         int res = 0;
1049         ast_mutex_lock(&chan->lock);
1050         /* Stop if we're a zombie or need a soft hangup */
1051         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1052                 ast_mutex_unlock(&chan->lock);
1053                 return -1;
1054         }
1055         switch(chan->_state) {
1056         case AST_STATE_RINGING:
1057         case AST_STATE_RING:
1058                 if (chan->tech->answer)
1059                         res = chan->tech->answer(chan);
1060                 ast_setstate(chan, AST_STATE_UP);
1061                 if (chan->cdr)
1062                         ast_cdr_answer(chan->cdr);
1063                 ast_mutex_unlock(&chan->lock);
1064                 return res;
1065                 break;
1066         case AST_STATE_UP:
1067                 if (chan->cdr)
1068                         ast_cdr_answer(chan->cdr);
1069                 break;
1070         }
1071         ast_mutex_unlock(&chan->lock);
1072         return 0;
1073 }
1074
1075
1076
1077 void ast_deactivate_generator(struct ast_channel *chan)
1078 {
1079         ast_mutex_lock(&chan->lock);
1080         if (chan->generatordata) {
1081                 if (chan->generator && chan->generator->release) 
1082                         chan->generator->release(chan, chan->generatordata);
1083                 chan->generatordata = NULL;
1084                 chan->generator = NULL;
1085                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1086                 ast_settimeout(chan, 0, NULL, NULL);
1087         }
1088         ast_mutex_unlock(&chan->lock);
1089 }
1090
1091 static int generator_force(void *data)
1092 {
1093         /* Called if generator doesn't have data */
1094         void *tmp;
1095         int res;
1096         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1097         struct ast_channel *chan = data;
1098         tmp = chan->generatordata;
1099         chan->generatordata = NULL;
1100         generate = chan->generator->generate;
1101         res = generate(chan, tmp, 0, 160);
1102         chan->generatordata = tmp;
1103         if (res) {
1104                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1105                 ast_deactivate_generator(chan);
1106         }
1107         return 0;
1108 }
1109
1110 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1111 {
1112         int res = 0;
1113         ast_mutex_lock(&chan->lock);
1114         if (chan->generatordata) {
1115                 if (chan->generator && chan->generator->release)
1116                         chan->generator->release(chan, chan->generatordata);
1117                 chan->generatordata = NULL;
1118         }
1119         ast_prod(chan);
1120         if ((chan->generatordata = gen->alloc(chan, params))) {
1121                 ast_settimeout(chan, 160, generator_force, chan);
1122                 chan->generator = gen;
1123         } else {
1124                 res = -1;
1125         }
1126         ast_mutex_unlock(&chan->lock);
1127         return res;
1128 }
1129
1130 /*--- ast_waitfor_n_fd: Wait for x amount of time on a file descriptor to have input.  */
1131 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1132 {
1133         struct timeval start = { 0 , 0 };
1134         int res;
1135         int x, y;
1136         int winner = -1;
1137         int spoint;
1138         struct pollfd *pfds;
1139         
1140         pfds = alloca(sizeof(struct pollfd) * n);
1141         if (!pfds) {
1142                 ast_log(LOG_ERROR, "Out of memory\n");
1143                 return -1;
1144         }
1145         if (*ms > 0)
1146                 start = ast_tvnow();
1147         y = 0;
1148         for (x=0; x < n; x++) {
1149                 if (fds[x] > -1) {
1150                         pfds[y].fd = fds[x];
1151                         pfds[y].events = POLLIN | POLLPRI;
1152                         y++;
1153                 }
1154         }
1155         res = poll(pfds, y, *ms);
1156         if (res < 0) {
1157                 /* Simulate a timeout if we were interrupted */
1158                 if (errno != EINTR)
1159                         *ms = -1;
1160                 else
1161                         *ms = 0;
1162                 return -1;
1163         }
1164         spoint = 0;
1165         for (x=0; x < n; x++) {
1166                 if (fds[x] > -1) {
1167                         if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1168                                 winner = fds[x];
1169                                 if (exception) {
1170                                         if (res & POLLPRI)
1171                                                 *exception = -1;
1172                                         else
1173                                                 *exception = 0;
1174                                 }
1175                         }
1176                 }
1177         }
1178         if (*ms > 0) {
1179                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1180                 if (*ms < 0)
1181                         *ms = 0;
1182         }
1183         return winner;
1184 }
1185
1186 /*--- ast_waitfor_nanfds: Wait for x amount of time on a file descriptor to have input.  */
1187 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
1188         int *exception, int *outfd, int *ms)
1189 {
1190         struct timeval start;
1191         struct pollfd *pfds;
1192         int res;
1193         long rms;
1194         int x, y, max;
1195         int spoint;
1196         time_t now = 0;
1197         long whentohangup = 0, havewhen = 0, diff;
1198         struct ast_channel *winner = NULL;
1199
1200         pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1201         if (!pfds) {
1202                 ast_log(LOG_ERROR, "Out of memory\n");
1203                 *outfd = -1;
1204                 return NULL;
1205         }
1206
1207         if (outfd)
1208                 *outfd = -99999;
1209         if (exception)
1210                 *exception = 0;
1211         
1212         /* Perform any pending masquerades */
1213         for (x=0; x < n; x++) {
1214                 ast_mutex_lock(&c[x]->lock);
1215                 if (c[x]->whentohangup) {
1216                         if (!havewhen)
1217                                 time(&now);
1218                         diff = c[x]->whentohangup - now;
1219                         if (!havewhen || (diff < whentohangup)) {
1220                                 havewhen++;
1221                                 whentohangup = diff;
1222                         }
1223                 }
1224                 if (c[x]->masq) {
1225                         if (ast_do_masquerade(c[x])) {
1226                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1227                                 *ms = -1;
1228                                 ast_mutex_unlock(&c[x]->lock);
1229                                 return NULL;
1230                         }
1231                 }
1232                 ast_mutex_unlock(&c[x]->lock);
1233         }
1234
1235         rms = *ms;
1236         
1237         if (havewhen) {
1238                 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1239                         rms =  whentohangup * 1000;
1240                 }
1241         }
1242         max = 0;
1243         for (x=0; x < n; x++) {
1244                 for (y=0; y< AST_MAX_FDS; y++) {
1245                         if (c[x]->fds[y] > -1) {
1246                                 pfds[max].fd = c[x]->fds[y];
1247                                 pfds[max].events = POLLIN | POLLPRI;
1248                                 max++;
1249                         }
1250                 }
1251                 CHECK_BLOCKING(c[x]);
1252         }
1253         for (x=0; x < nfds; x++) {
1254                 if (fds[x] > -1) {
1255                         pfds[max].fd = fds[x];
1256                         pfds[max].events = POLLIN | POLLPRI;
1257                         max++;
1258                 }
1259         }
1260         if (*ms > 0) 
1261                 start = ast_tvnow();
1262         res = poll(pfds, max, rms);
1263         if (res < 0) {
1264                 for (x=0; x < n; x++) 
1265                         ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1266                 /* Simulate a timeout if we were interrupted */
1267                 if (errno != EINTR)
1268                         *ms = -1;
1269                 else {
1270                         /* Just an interrupt */
1271 #if 0
1272                         *ms = 0;
1273 #endif                  
1274                 }
1275                 return NULL;
1276         } else {
1277                 /* If no fds signalled, then timeout. So set ms = 0
1278                    since we may not have an exact timeout.
1279                 */
1280                 if (res == 0)
1281                         *ms = 0;
1282         }
1283
1284         if (havewhen)
1285                 time(&now);
1286         spoint = 0;
1287         for (x=0; x < n; x++) {
1288                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1289                 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1290                         c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1291                         if (!winner)
1292                                 winner = c[x];
1293                 }
1294                 for (y=0; y < AST_MAX_FDS; y++) {
1295                         if (c[x]->fds[y] > -1) {
1296                                 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1297                                         if (res & POLLPRI)
1298                                                 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1299                                         else
1300                                                 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1301                                         c[x]->fdno = y;
1302                                         winner = c[x];
1303                                 }
1304                         }
1305                 }
1306         }
1307         for (x=0; x < nfds; x++) {
1308                 if (fds[x] > -1) {
1309                         if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1310                                 if (outfd)
1311                                         *outfd = fds[x];
1312                                 if (exception) {        
1313                                         if (res & POLLPRI) 
1314                                                 *exception = -1;
1315                                         else
1316                                                 *exception = 0;
1317                                 }
1318                                 winner = NULL;
1319                         }
1320                 }       
1321         }
1322         if (*ms > 0) {
1323                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1324                 if (*ms < 0)
1325                         *ms = 0;
1326         }
1327         return winner;
1328 }
1329
1330 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1331 {
1332         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1333 }
1334
1335 int ast_waitfor(struct ast_channel *c, int ms)
1336 {
1337         struct ast_channel *chan;
1338         int oldms = ms;
1339
1340         chan = ast_waitfor_n(&c, 1, &ms);
1341         if (ms < 0) {
1342                 if (oldms < 0)
1343                         return 0;
1344                 else
1345                         return -1;
1346         }
1347         return ms;
1348 }
1349
1350 int ast_waitfordigit(struct ast_channel *c, int ms)
1351 {
1352         /* XXX Should I be merged with waitfordigit_full XXX */
1353         struct ast_frame *f;
1354         int result = 0;
1355
1356         /* Stop if we're a zombie or need a soft hangup */
1357         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1358                 return -1;
1359
1360         /* Wait for a digit, no more than ms milliseconds total. */
1361         while(ms && !result) {
1362                 ms = ast_waitfor(c, ms);
1363                 if (ms < 0) /* Error */
1364                         result = -1; 
1365                 else if (ms > 0) {
1366                         /* Read something */
1367                         f = ast_read(c);
1368                         if (f) {
1369                                 if (f->frametype == AST_FRAME_DTMF) 
1370                                         result = f->subclass;
1371                                 ast_frfree(f);
1372                         } else
1373                                 result = -1;
1374                 }
1375         }
1376         return result;
1377 }
1378
1379 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1380 {
1381         int res = -1;
1382 #ifdef ZAPTEL_OPTIMIZATIONS
1383         if (c->timingfd > -1) {
1384                 if (!func) {
1385                         samples = 0;
1386                         data = 0;
1387                 }
1388                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1389                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1390                 c->timingfunc = func;
1391                 c->timingdata = data;
1392         }
1393 #endif  
1394         return res;
1395 }
1396
1397 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1398 {
1399         struct ast_frame *f;
1400         struct ast_channel *rchan;
1401         int outfd;
1402         int res;
1403
1404         /* Stop if we're a zombie or need a soft hangup */
1405         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1406                 return -1;
1407         /* Wait for a digit, no more than ms milliseconds total. */
1408         while(ms) {
1409                 errno = 0;
1410                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1411                 if ((!rchan) && (outfd < 0) && (ms)) { 
1412                         if (errno == 0 || errno == EINTR)
1413                                 continue;
1414                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1415                         return -1;
1416                 } else if (outfd > -1) {
1417                         /* The FD we were watching has something waiting */
1418                         return 1;
1419                 } else if (rchan) {
1420                         f = ast_read(c);
1421                         if(!f) {
1422                                 return -1;
1423                         }
1424
1425                         switch(f->frametype) {
1426                         case AST_FRAME_DTMF:
1427                                 res = f->subclass;
1428                                 ast_frfree(f);
1429                                 return res;
1430                         case AST_FRAME_CONTROL:
1431                                 switch(f->subclass) {
1432                                 case AST_CONTROL_HANGUP:
1433                                         ast_frfree(f);
1434                                         return -1;
1435                                 case AST_CONTROL_RINGING:
1436                                 case AST_CONTROL_ANSWER:
1437                                         /* Unimportant */
1438                                         break;
1439                                 default:
1440                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1441                                 }
1442                         case AST_FRAME_VOICE:
1443                                 /* Write audio if appropriate */
1444                                 if (audiofd > -1)
1445                                         write(audiofd, f->data, f->datalen);
1446                         }
1447                         /* Ignore */
1448                         ast_frfree(f);
1449                 }
1450         }
1451         return 0; /* Time is up */
1452 }
1453
1454 struct ast_frame *ast_read(struct ast_channel *chan)
1455 {
1456         struct ast_frame *f = NULL;
1457         int blah;
1458         int prestate;
1459 #ifdef ZAPTEL_OPTIMIZATIONS
1460         int (*func)(void *);
1461         void *data;
1462         int res;
1463 #endif
1464         static struct ast_frame null_frame = {
1465                 AST_FRAME_NULL,
1466         };
1467         
1468         ast_mutex_lock(&chan->lock);
1469         if (chan->masq) {
1470                 if (ast_do_masquerade(chan)) {
1471                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1472                         f = NULL;
1473                 } else
1474                         f =  &null_frame;
1475                 ast_mutex_unlock(&chan->lock);
1476                 return f;
1477         }
1478
1479         /* Stop if we're a zombie or need a soft hangup */
1480         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1481                 if (chan->generator)
1482                         ast_deactivate_generator(chan);
1483                 ast_mutex_unlock(&chan->lock);
1484                 return NULL;
1485         }
1486         prestate = chan->_state;
1487
1488         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1489                 /* We have DTMF that has been deferred.  Return it now */
1490                 chan->dtmff.frametype = AST_FRAME_DTMF;
1491                 chan->dtmff.subclass = chan->dtmfq[0];
1492                 /* Drop first digit */
1493                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1494                 ast_mutex_unlock(&chan->lock);
1495                 return &chan->dtmff;
1496         }
1497         
1498         /* Read and ignore anything on the alertpipe, but read only
1499            one sizeof(blah) per frame that we send from it */
1500         if (chan->alertpipe[0] > -1) {
1501                 read(chan->alertpipe[0], &blah, sizeof(blah));
1502         }
1503 #ifdef ZAPTEL_OPTIMIZATIONS
1504         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1505                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1506                 blah = -1;
1507                 /* IF we can't get event, assume it's an expired as-per the old interface */
1508                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1509                 if (res) 
1510                         blah = ZT_EVENT_TIMER_EXPIRED;
1511
1512                 if (blah == ZT_EVENT_TIMER_PING) {
1513 #if 0
1514                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1515 #endif                  
1516                         if (!chan->readq || !chan->readq->next) {
1517                                 /* Acknowledge PONG unless we need it again */
1518 #if 0
1519                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1520 #endif                          
1521                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1522                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1523                                 }
1524                         }
1525                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1526                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1527                         func = chan->timingfunc;
1528                         data = chan->timingdata;
1529                         ast_mutex_unlock(&chan->lock);
1530                         if (func) {
1531 #if 0
1532                                 ast_log(LOG_DEBUG, "Calling private function\n");
1533 #endif                  
1534                                 func(data);
1535                         } else {
1536                                 blah = 0;
1537                                 ast_mutex_lock(&chan->lock);
1538                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1539                                 chan->timingdata = NULL;
1540                                 ast_mutex_unlock(&chan->lock);
1541                         }
1542                         f =  &null_frame;
1543                         return f;
1544                 } else
1545                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1546         }
1547 #endif
1548         /* Check for pending read queue */
1549         if (chan->readq) {
1550                 f = chan->readq;
1551                 chan->readq = f->next;
1552                 /* Interpret hangup and return NULL */
1553                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1554                         ast_frfree(f);
1555                         f = NULL;
1556                 }
1557         } else {
1558                 chan->blocker = pthread_self();
1559                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1560                         if (chan->tech->exception) 
1561                                 f = chan->tech->exception(chan);
1562                         else {
1563                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1564                                 f = &null_frame;
1565                         }
1566                         /* Clear the exception flag */
1567                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1568                 } else {
1569                         if (chan->tech->read)
1570                                 f = chan->tech->read(chan);
1571                         else
1572                                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1573                 }
1574         }
1575
1576
1577         if (f && (f->frametype == AST_FRAME_VOICE)) {
1578                 if (!(f->subclass & chan->nativeformats)) {
1579                         /* This frame can't be from the current native formats -- drop it on the
1580                            floor */
1581                         ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n", chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
1582                         ast_frfree(f);
1583                         f = &null_frame;
1584                 } else {
1585                         if (chan->spiers) {
1586                                 struct ast_channel_spy *spying;
1587                                 for (spying = chan->spiers; spying; spying=spying->next) {
1588                                         ast_queue_spy_frame(spying, f, 0);
1589                                 }
1590                         }
1591                         if (chan->monitor && chan->monitor->read_stream ) {
1592 #ifndef MONITOR_CONSTANT_DELAY
1593                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1594                                 if (jump >= 0) {
1595                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1596                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1597                                         chan->insmpl += jump + 2 * f->samples;
1598                                 } else
1599                                         chan->insmpl+= f->samples;
1600 #else
1601                                 int jump = chan->outsmpl - chan->insmpl;
1602                                 if (jump - MONITOR_DELAY >= 0) {
1603                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1604                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1605                                         chan->insmpl += jump;
1606                                 } else
1607                                         chan->insmpl += f->samples;
1608 #endif
1609                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1610                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1611                         }
1612                         if (chan->readtrans) {
1613                                 f = ast_translate(chan->readtrans, f, 1);
1614                                 if (!f)
1615                                         f = &null_frame;
1616                         }
1617                 }
1618         }
1619
1620         /* Make sure we always return NULL in the future */
1621         if (!f) {
1622                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1623                 if (chan->generator)
1624                         ast_deactivate_generator(chan);
1625                 /* End the CDR if appropriate */
1626                 if (chan->cdr)
1627                         ast_cdr_end(chan->cdr);
1628         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1629                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1630                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1631                 else
1632                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1633                 f = &null_frame;
1634         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1635                 if (prestate == AST_STATE_UP) {
1636                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1637                         f = &null_frame;
1638                 }
1639                 /* Answer the CDR */
1640                 ast_setstate(chan, AST_STATE_UP);
1641                 ast_cdr_answer(chan->cdr);
1642         } 
1643
1644         /* Run any generator sitting on the line */
1645         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1646                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1647                    will be calling the generator instead */
1648                 void *tmp;
1649                 int res;
1650                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1651
1652                 if (chan->timingfunc) {
1653                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1654                         ast_settimeout(chan, 0, NULL, NULL);
1655                 }
1656                 tmp = chan->generatordata;
1657                 chan->generatordata = NULL;
1658                 generate = chan->generator->generate;
1659                 res = generate(chan, tmp, f->datalen, f->samples);
1660                 chan->generatordata = tmp;
1661                 if (res) {
1662                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1663                         ast_deactivate_generator(chan);
1664                 }
1665         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1666                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1667                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1668                         ast_settimeout(chan, 160, generator_force, chan);
1669                 }
1670         }
1671         /* High bit prints debugging */
1672         if (chan->fin & 0x80000000)
1673                 ast_frame_dump(chan->name, f, "<<");
1674         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1675                 chan->fin &= 0x80000000;
1676         else
1677                 chan->fin++;
1678         ast_mutex_unlock(&chan->lock);
1679         return f;
1680 }
1681
1682 int ast_indicate(struct ast_channel *chan, int condition)
1683 {
1684         int res = -1;
1685
1686         /* Stop if we're a zombie or need a soft hangup */
1687         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1688                 return -1;
1689         ast_mutex_lock(&chan->lock);
1690         if (chan->tech->indicate)
1691                 res = chan->tech->indicate(chan, condition);
1692         ast_mutex_unlock(&chan->lock);
1693         if (!chan->tech->indicate || res) {
1694                 /*
1695                  * Device does not support (that) indication, lets fake
1696                  * it by doing our own tone generation. (PM2002)
1697                  */
1698                 if (condition >= 0) {
1699                         const struct tone_zone_sound *ts = NULL;
1700                         switch (condition) {
1701                         case AST_CONTROL_RINGING:
1702                                 ts = ast_get_indication_tone(chan->zone, "ring");
1703                                 break;
1704                         case AST_CONTROL_BUSY:
1705                                 ts = ast_get_indication_tone(chan->zone, "busy");
1706                                 break;
1707                         case AST_CONTROL_CONGESTION:
1708                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1709                                 break;
1710                         }
1711                         if (ts && ts->data[0]) {
1712                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1713                                 ast_playtones_start(chan,0,ts->data, 1);
1714                                 res = 0;
1715                         } else if (condition == AST_CONTROL_PROGRESS) {
1716                                 /* ast_playtones_stop(chan); */
1717                         } else if (condition == AST_CONTROL_PROCEEDING) {
1718                                 /* Do nothing, really */
1719                         } else if (condition == AST_CONTROL_HOLD) {
1720                                 /* Do nothing.... */
1721                         } else if (condition == AST_CONTROL_UNHOLD) {
1722                                 /* Do nothing.... */
1723                         } else {
1724                                 /* not handled */
1725                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1726                                 res = -1;
1727                         }
1728                 }
1729                 else ast_playtones_stop(chan);
1730         }
1731         return res;
1732 }
1733
1734 int ast_recvchar(struct ast_channel *chan, int timeout)
1735 {
1736         int c;
1737         char *buf = ast_recvtext(chan, timeout);
1738         if (buf == NULL)
1739                 return -1;      /* error or timeout */
1740         c = *(unsigned char *)buf;
1741         free(buf);
1742         return c;
1743 }
1744
1745 char *ast_recvtext(struct ast_channel *chan, int timeout)
1746 {
1747         int res, done = 0;
1748         char *buf = NULL;
1749         
1750         while (!done) {
1751                 struct ast_frame *f;
1752                 if (ast_check_hangup(chan))
1753                         break;
1754                 res = ast_waitfor(chan, timeout);
1755                 if (res <= 0) /* timeout or error */
1756                         break;
1757                 timeout = res;  /* update timeout */
1758                 f = ast_read(chan);
1759                 if (f == NULL)
1760                         break; /* no frame */
1761                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
1762                         done = 1;       /* force a break */
1763                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
1764                         buf = strndup((char *) f->data, f->datalen);    /* dup and break */
1765                         done = 1;
1766                 }
1767                 ast_frfree(f);
1768         }
1769         return buf;
1770 }
1771
1772 int ast_sendtext(struct ast_channel *chan, char *text)
1773 {
1774         int res = 0;
1775         /* Stop if we're a zombie or need a soft hangup */
1776         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1777                 return -1;
1778         CHECK_BLOCKING(chan);
1779         if (chan->tech->send_text)
1780                 res = chan->tech->send_text(chan, text);
1781         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1782         return res;
1783 }
1784
1785 static int do_senddigit(struct ast_channel *chan, char digit)
1786 {
1787         int res = -1;
1788
1789         if (chan->tech->send_digit)
1790                 res = chan->tech->send_digit(chan, digit);
1791         if (!chan->tech->send_digit || res) {
1792                 /*
1793                  * Device does not support DTMF tones, lets fake
1794                  * it by doing our own generation. (PM2002)
1795                  */
1796                 static const char* dtmf_tones[] = {
1797                         "!941+1336/100,!0/100", /* 0 */
1798                         "!697+1209/100,!0/100", /* 1 */
1799                         "!697+1336/100,!0/100", /* 2 */
1800                         "!697+1477/100,!0/100", /* 3 */
1801                         "!770+1209/100,!0/100", /* 4 */
1802                         "!770+1336/100,!0/100", /* 5 */
1803                         "!770+1477/100,!0/100", /* 6 */
1804                         "!852+1209/100,!0/100", /* 7 */
1805                         "!852+1336/100,!0/100", /* 8 */
1806                         "!852+1477/100,!0/100", /* 9 */
1807                         "!697+1633/100,!0/100", /* A */
1808                         "!770+1633/100,!0/100", /* B */
1809                         "!852+1633/100,!0/100", /* C */
1810                         "!941+1633/100,!0/100", /* D */
1811                         "!941+1209/100,!0/100", /* * */
1812                         "!941+1477/100,!0/100" };       /* # */
1813                 if (digit >= '0' && digit <='9')
1814                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
1815                 else if (digit >= 'A' && digit <= 'D')
1816                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
1817                 else if (digit == '*')
1818                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
1819                 else if (digit == '#')
1820                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
1821                 else {
1822                         /* not handled */
1823                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
1824                 }
1825         }
1826         return 0;
1827 }
1828
1829 int ast_senddigit(struct ast_channel *chan, char digit)
1830 {
1831         return do_senddigit(chan, digit);
1832 }
1833
1834 int ast_prod(struct ast_channel *chan)
1835 {
1836         struct ast_frame a = { AST_FRAME_VOICE };
1837         char nothing[128];
1838
1839         /* Send an empty audio frame to get things moving */
1840         if (chan->_state != AST_STATE_UP) {
1841                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1842                 a.subclass = chan->rawwriteformat;
1843                 a.data = nothing + AST_FRIENDLY_OFFSET;
1844                 a.src = "ast_prod";
1845                 if (ast_write(chan, &a))
1846                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1847         }
1848         return 0;
1849 }
1850
1851 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1852 {
1853         int res;
1854         if (!chan->tech->write_video)
1855                 return 0;
1856         res = ast_write(chan, fr);
1857         if (!res)
1858                 res = 1;
1859         return res;
1860 }
1861
1862 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1863 {
1864         int res = -1;
1865         struct ast_frame *f = NULL;
1866         /* Stop if we're a zombie or need a soft hangup */
1867         ast_mutex_lock(&chan->lock);
1868         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1869                 ast_mutex_unlock(&chan->lock);
1870                 return -1;
1871         }
1872         /* Handle any pending masquerades */
1873         if (chan->masq) {
1874                 if (ast_do_masquerade(chan)) {
1875                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1876                         ast_mutex_unlock(&chan->lock);
1877                         return -1;
1878                 }
1879         }
1880         if (chan->masqr) {
1881                 ast_mutex_unlock(&chan->lock);
1882                 return 0;
1883         }
1884         if (chan->generatordata) {
1885                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1886                         ast_deactivate_generator(chan);
1887                 else {
1888                         ast_mutex_unlock(&chan->lock);
1889                         return 0;
1890                 }
1891         }
1892         /* High bit prints debugging */
1893         if (chan->fout & 0x80000000)
1894                 ast_frame_dump(chan->name, fr, ">>");
1895         CHECK_BLOCKING(chan);
1896         switch(fr->frametype) {
1897         case AST_FRAME_CONTROL:
1898                 /* XXX Interpret control frames XXX */
1899                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1900                 break;
1901         case AST_FRAME_DTMF:
1902                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1903                 ast_mutex_unlock(&chan->lock);
1904                 res = do_senddigit(chan,fr->subclass);
1905                 ast_mutex_lock(&chan->lock);
1906                 CHECK_BLOCKING(chan);
1907                 break;
1908         case AST_FRAME_TEXT:
1909                 if (chan->tech->send_text)
1910                         res = chan->tech->send_text(chan, (char *) fr->data);
1911                 else
1912                         res = 0;
1913                 break;
1914         case AST_FRAME_HTML:
1915                 if (chan->tech->send_html)
1916                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1917                 else
1918                         res = 0;
1919                 break;
1920         case AST_FRAME_VIDEO:
1921                 /* XXX Handle translation of video codecs one day XXX */
1922                 if (chan->tech->write_video)
1923                         res = chan->tech->write_video(chan, fr);
1924                 else
1925                         res = 0;
1926                 break;
1927         default:
1928                 if (chan->tech->write) {
1929                         if (chan->writetrans) 
1930                                 f = ast_translate(chan->writetrans, fr, 0);
1931                         else
1932                                 f = fr;
1933                         if (f) {
1934                                 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1935                                         struct ast_channel_spy *spying;
1936                                         for (spying = chan->spiers; spying; spying=spying->next) {
1937                                                 ast_queue_spy_frame(spying, f, 1);
1938                                         }
1939                                 }
1940
1941                                 if( chan->monitor && chan->monitor->write_stream &&
1942                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1943 #ifndef MONITOR_CONSTANT_DELAY
1944                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1945                                         if (jump >= 0) {
1946                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1947                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1948                                                 chan->outsmpl += jump + 2 * f->samples;
1949                                         } else
1950                                                 chan->outsmpl += f->samples;
1951 #else
1952                                         int jump = chan->insmpl - chan->outsmpl;
1953                                         if (jump - MONITOR_DELAY >= 0) {
1954                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1955                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1956                                                 chan->outsmpl += jump;
1957                                         } else
1958                                                 chan->outsmpl += f->samples;
1959 #endif
1960                                         if (ast_writestream(chan->monitor->write_stream, f) < 0)
1961                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1962                                 }
1963
1964                                 res = chan->tech->write(chan, f);
1965                         } else
1966                                 res = 0;
1967                 }
1968         }
1969         if (f && (f != fr))
1970                 ast_frfree(f);
1971         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1972         /* Consider a write failure to force a soft hangup */
1973         if (res < 0)
1974                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1975         else {
1976                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1977                         chan->fout &= 0x80000000;
1978                 else
1979                         chan->fout++;
1980         }
1981         ast_mutex_unlock(&chan->lock);
1982         return res;
1983 }
1984
1985 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1986                       struct ast_trans_pvt **trans, const int direction)
1987 {
1988         int native;
1989         int res;
1990         
1991         native = chan->nativeformats;
1992         /* Find a translation path from the native format to one of the desired formats */
1993         if (!direction)
1994                 /* reading */
1995                 res = ast_translator_best_choice(&fmt, &native);
1996         else
1997                 /* writing */
1998                 res = ast_translator_best_choice(&native, &fmt);
1999
2000         if (res < 0) {
2001                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2002                         ast_getformatname(native), ast_getformatname(fmt));
2003                 return -1;
2004         }
2005         
2006         /* Now we have a good choice for both. */
2007         ast_mutex_lock(&chan->lock);
2008         *rawformat = native;
2009         /* User perspective is fmt */
2010         *format = fmt;
2011         /* Free any read translation we have right now */
2012         if (*trans)
2013                 ast_translator_free_path(*trans);
2014         /* Build a translation path from the raw format to the desired format */
2015         if (!direction)
2016                 /* reading */
2017                 *trans = ast_translator_build_path(*format, *rawformat);
2018         else
2019                 /* writing */
2020                 *trans = ast_translator_build_path(*rawformat, *format);
2021         ast_mutex_unlock(&chan->lock);
2022         if (option_debug)
2023                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2024                         direction ? "write" : "read", ast_getformatname(fmt));
2025         return 0;
2026 }
2027
2028 int ast_set_read_format(struct ast_channel *chan, int fmt)
2029 {
2030         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2031                           &chan->readtrans, 0);
2032 }
2033
2034 int ast_set_write_format(struct ast_channel *chan, int fmt)
2035 {
2036         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2037                           &chan->writetrans, 1);
2038 }
2039
2040 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
2041 {
2042         int state = 0;
2043         int cause = 0;
2044         struct ast_channel *chan;
2045         struct ast_frame *f;
2046         int res = 0;
2047         
2048         chan = ast_request(type, format, data, &cause);
2049         if (chan) {
2050                 if (oh) {
2051                         ast_set_variables(chan, oh->vars);
2052                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2053                 }
2054                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2055
2056                 if (!ast_call(chan, data, 0)) {
2057                         while(timeout && (chan->_state != AST_STATE_UP)) {
2058                                 res = ast_waitfor(chan, timeout);
2059                                 if (res < 0) {
2060                                         /* Something not cool, or timed out */
2061                                         break;
2062                                 }
2063                                 /* If done, break out */
2064                                 if (!res)
2065                                         break;
2066                                 if (timeout > -1)
2067                                         timeout = res;
2068                                 f = ast_read(chan);
2069                                 if (!f) {
2070                                         state = AST_CONTROL_HANGUP;
2071                                         res = 0;
2072                                         break;
2073                                 }
2074                                 if (f->frametype == AST_FRAME_CONTROL) {
2075                                         if (f->subclass == AST_CONTROL_RINGING)
2076                                                 state = AST_CONTROL_RINGING;
2077                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2078                                                 state = f->subclass;
2079                                                 ast_frfree(f);
2080                                                 break;
2081                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
2082                                                 state = f->subclass;
2083                                                 ast_frfree(f);
2084                                                 break;
2085                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
2086                                                 /* Ignore */
2087                                         } else if (f->subclass == -1) {
2088                                                 /* Ignore -- just stopping indications */
2089                                         } else {
2090                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2091                                         }
2092                                 }
2093                                 ast_frfree(f);
2094                         }
2095                 } else
2096                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2097         } else {
2098                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2099                 switch(cause) {
2100                 case AST_CAUSE_BUSY:
2101                         state = AST_CONTROL_BUSY;
2102                         break;
2103                 case AST_CAUSE_CONGESTION:
2104                         state = AST_CONTROL_CONGESTION;
2105                         break;
2106                 }
2107         }
2108         if (chan) {
2109                 /* Final fixups */
2110                 if (oh) {
2111                         if (oh->context && *oh->context)
2112                                 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2113                         if (oh->exten && *oh->exten)
2114                                 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2115                         if (oh->priority)       
2116                                 chan->priority = oh->priority;
2117                 }
2118                 if (chan->_state == AST_STATE_UP) 
2119                         state = AST_CONTROL_ANSWER;
2120         }
2121         if (outstate)
2122                 *outstate = state;
2123         if (chan && res <= 0) {
2124                 if (!chan->cdr) {
2125                         chan->cdr = ast_cdr_alloc();
2126                         if (chan->cdr)
2127                                 ast_cdr_init(chan->cdr, chan);
2128                 }
2129                 if (chan->cdr) {
2130                         char tmp[256];
2131                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
2132                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2133                         ast_cdr_update(chan);
2134                         ast_cdr_start(chan->cdr);
2135                         ast_cdr_end(chan->cdr);
2136                         /* If the cause wasn't handled properly */
2137                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2138                                 ast_cdr_failed(chan->cdr);
2139                 } else 
2140                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2141                 ast_hangup(chan);
2142                 chan = NULL;
2143         }
2144         return chan;
2145 }
2146
2147 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2148 {
2149         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2150 }
2151
2152 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2153 {
2154         struct chanlist *chan;
2155         struct ast_channel *c = NULL;
2156         int capabilities;
2157         int fmt;
2158         int res;
2159         int foo;
2160
2161         if (!cause)
2162                 cause = &foo;
2163         *cause = AST_CAUSE_NOTDEFINED;
2164         if (ast_mutex_lock(&chlock)) {
2165                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2166                 return NULL;
2167         }
2168         chan = backends;
2169         while(chan) {
2170                 if (!strcasecmp(type, chan->tech->type)) {
2171                         capabilities = chan->tech->capabilities;
2172                         fmt = format;
2173                         res = ast_translator_best_choice(&fmt, &capabilities);
2174                         if (res < 0) {
2175                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2176                                 ast_mutex_unlock(&chlock);
2177                                 return NULL;
2178                         }
2179                         ast_mutex_unlock(&chlock);
2180                         if (chan->tech->requester)
2181                                 c = chan->tech->requester(type, capabilities, data, cause);
2182                         if (c) {
2183                                 if (c->_state == AST_STATE_DOWN) {
2184                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2185                                         "Channel: %s\r\n"
2186                                         "State: %s\r\n"
2187                                         "CallerID: %s\r\n"
2188                                         "CallerIDName: %s\r\n"
2189                                         "Uniqueid: %s\r\n",
2190                                         c->name, ast_state2str(c->_state), c->cid.cid_num ? c->cid.cid_num : "<unknown>", c->cid.cid_name ? c->cid.cid_name : "<unknown>",c->uniqueid);
2191                                 }
2192                         }
2193                         return c;
2194                 }
2195                 chan = chan->next;
2196         }
2197         if (!chan) {
2198                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2199                 *cause = AST_CAUSE_NOSUCHDRIVER;
2200         }
2201         ast_mutex_unlock(&chlock);
2202         return c;
2203 }
2204
2205 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2206 {
2207         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2208            If the remote end does not answer within the timeout, then do NOT hang up, but 
2209            return anyway.  */
2210         int res = -1;
2211         /* Stop if we're a zombie or need a soft hangup */
2212         ast_mutex_lock(&chan->lock);
2213         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2214                 if (chan->tech->call)
2215                         res = chan->tech->call(chan, addr, timeout);
2216         ast_mutex_unlock(&chan->lock);
2217         return res;
2218 }
2219
2220 /*--- ast_transfer: Transfer a call to dest, if the channel supports transfer */
2221 /*      called by app_transfer or the manager interface */
2222 int ast_transfer(struct ast_channel *chan, char *dest) 
2223 {
2224         int res = -1;
2225
2226         /* Stop if we're a zombie or need a soft hangup */
2227         ast_mutex_lock(&chan->lock);
2228         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2229                 if (chan->tech->transfer) {
2230                         res = chan->tech->transfer(chan, dest);
2231                         if (!res)
2232                                 res = 1;
2233                 } else
2234                         res = 0;
2235         }
2236         ast_mutex_unlock(&chan->lock);
2237         return res;
2238 }
2239
2240 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2241 {
2242         int pos=0;
2243         int to = ftimeout;
2244         int d;
2245
2246         /* XXX Merge with full version? XXX */
2247         /* Stop if we're a zombie or need a soft hangup */
2248         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2249                 return -1;
2250         if (!len)
2251                 return -1;
2252         do {
2253                 if (c->stream) {
2254                         d = ast_waitstream(c, AST_DIGIT_ANY);
2255                         ast_stopstream(c);
2256                         usleep(1000);
2257                         if (!d)
2258                                 d = ast_waitfordigit(c, to);
2259                 } else {
2260                         d = ast_waitfordigit(c, to);
2261                 }
2262                 if (d < 0)
2263                         return -1;
2264                 if (d == 0) {
2265                         s[pos]='\0';
2266                         return 1;
2267                 }
2268                 if (!strchr(enders, d))
2269                         s[pos++] = d;
2270                 if (strchr(enders, d) || (pos >= len)) {
2271                         s[pos]='\0';
2272                         return 0;
2273                 }
2274                 to = timeout;
2275         } while(1);
2276         /* Never reached */
2277         return 0;
2278 }
2279
2280 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2281 {
2282         int pos=0;
2283         int to = ftimeout;
2284         int d;
2285
2286         /* Stop if we're a zombie or need a soft hangup */
2287         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2288                 return -1;
2289         if (!len)
2290                 return -1;
2291         do {
2292                 if (c->stream) {
2293                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2294                         ast_stopstream(c);
2295                         usleep(1000);
2296                         if (!d)
2297                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2298                 } else {
2299                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2300                 }
2301                 if (d < 0)
2302                         return -1;
2303                 if (d == 0) {
2304                         s[pos]='\0';
2305                         return 1;
2306                 }
2307                 if (d == 1) {
2308                         s[pos]='\0';
2309                         return 2;
2310                 }
2311                 if (!strchr(enders, d))
2312                         s[pos++] = d;
2313                 if (strchr(enders, d) || (pos >= len)) {
2314                         s[pos]='\0';
2315                         return 0;
2316                 }
2317                 to = timeout;
2318         } while(1);
2319         /* Never reached */
2320         return 0;
2321 }
2322
2323 int ast_channel_supports_html(struct ast_channel *chan)
2324 {
2325         if (chan->tech->send_html)
2326                 return 1;
2327         return 0;
2328 }
2329
2330 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2331 {
2332         if (chan->tech->send_html)
2333                 return chan->tech->send_html(chan, subclass, data, datalen);
2334         return -1;
2335 }
2336
2337 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2338 {
2339         if (chan->tech->send_html)
2340                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2341         return -1;
2342 }
2343
2344 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2345 {
2346         int src;
2347         int dst;
2348
2349         /* Set up translation from the chan to the peer */
2350         src = chan->nativeformats;
2351         dst = peer->nativeformats;
2352         if (ast_translator_best_choice(&dst, &src) < 0) {
2353                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2354                 return -1;
2355         }
2356
2357         /* if the best path is not 'pass through', then
2358            transcoding is needed; if desired, force transcode path
2359            to use SLINEAR between channels */
2360         if ((src != dst) && option_transcode_slin)
2361                 dst = AST_FORMAT_SLINEAR;
2362         if (ast_set_read_format(chan, dst) < 0) {
2363                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2364                 return -1;
2365         }
2366         if (ast_set_write_format(peer, dst) < 0) {
2367                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2368                 return -1;
2369         }
2370
2371         /* Set up translation from the peer to the chan */
2372         src = peer->nativeformats;
2373         dst = chan->nativeformats;
2374         if (ast_translator_best_choice(&dst, &src) < 0) {
2375                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2376                 return -1;
2377         }
2378         /* if the best path is not 'pass through', then
2379            transcoding is needed; if desired, force transcode path
2380            to use SLINEAR between channels */
2381         if ((src != dst) && option_transcode_slin)
2382                 dst = AST_FORMAT_SLINEAR;
2383         if (ast_set_read_format(peer, dst) < 0) {
2384                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2385                 return -1;
2386         }
2387         if (ast_set_write_format(chan, dst) < 0) {
2388                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2389                 return -1;
2390         }
2391         return 0;
2392 }
2393
2394 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2395 {
2396         struct ast_frame null = { AST_FRAME_NULL, };
2397         int res = -1;
2398
2399         if (original == clone) {
2400                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2401                 return -1;
2402         }
2403         ast_mutex_lock(&original->lock);
2404         while(ast_mutex_trylock(&clone->lock)) {
2405                 ast_mutex_unlock(&original->lock);
2406                 usleep(1);
2407                 ast_mutex_lock(&original->lock);
2408         }
2409         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2410                 clone->name, original->name);
2411         if (original->masq) {
2412                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2413                         original->masq->name, original->name);
2414         } else if (clone->masqr) {
2415                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2416                         clone->name, clone->masqr->name);
2417         } else {
2418                 original->masq = clone;
2419                 clone->masqr = original;
2420                 ast_queue_frame(original, &null);
2421                 ast_queue_frame(clone, &null);
2422                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2423                 res = 0;
2424         }
2425         ast_mutex_unlock(&clone->lock);
2426         ast_mutex_unlock(&original->lock);
2427         return res;
2428 }
2429
2430 void ast_change_name(struct ast_channel *chan, char *newname)
2431 {
2432         char tmp[256];
2433         ast_copy_string(tmp, chan->name, sizeof(tmp));
2434         ast_copy_string(chan->name, newname, sizeof(chan->name));
2435         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2436 }
2437
2438 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2439 {
2440         struct ast_var_t *current, *newvar;
2441         char *varname;
2442
2443         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2444                 int vartype = 0;
2445
2446                 varname = ast_var_full_name(current);
2447                 if (!varname)
2448                         continue;
2449
2450                 if (varname[0] == '_') {
2451                         vartype = 1;
2452                         if (varname[1] == '_')
2453                                 vartype = 2;
2454                 }
2455
2456                 switch (vartype) {
2457                 case 1:
2458                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2459                         if (newvar) {
2460                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2461                                 if (option_debug)
2462                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2463                         }
2464                         break;
2465                 case 2:
2466                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2467                         if (newvar) {
2468                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2469                                 if (option_debug)
2470                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2471                         }
2472                         break;
2473                 default:
2474                         if (option_debug)
2475                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2476                         break;
2477                 }
2478         }
2479 }
2480
2481 /* Clone channel variables from 'clone' channel into 'original' channel
2482    All variables except those related to app_groupcount are cloned
2483    Variables are actually _removed_ from 'clone' channel, presumably
2484    because it will subsequently be destroyed.
2485    Assumes locks will be in place on both channels when called.
2486 */
2487    
2488 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2489 {
2490         struct ast_var_t *varptr;
2491
2492         /* we need to remove all app_groupcount related variables from the original
2493            channel before merging in the clone's variables; any groups assigned to the
2494            original channel should be released, only those assigned to the clone
2495            should remain
2496         */
2497
2498         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2499                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2500                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2501                         ast_var_delete(varptr);
2502                 }
2503         }
2504         AST_LIST_TRAVERSE_SAFE_END;
2505
2506         /* Append variables from clone channel into original channel */
2507         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2508         if (AST_LIST_FIRST(&clone->varshead))
2509                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2510 }
2511
2512 /*--- ast_do_masquerade: Masquerade a channel */
2513 /* Assumes channel will be locked when called */
2514 int ast_do_masquerade(struct ast_channel *original)
2515 {
2516         int x,i;
2517         int res=0;
2518         int origstate;
2519         struct ast_frame *cur, *prev;
2520         const struct ast_channel_tech *t;
2521         void *t_pvt;
2522         struct ast_callerid tmpcid;
2523         struct ast_channel *clone = original->masq;
2524         int rformat = original->readformat;
2525         int wformat = original->writeformat;
2526         char newn[100];
2527         char orig[100];
2528         char masqn[100];
2529         char zombn[100];
2530
2531         if (option_debug > 3)
2532                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2533                         clone->name, clone->_state, original->name, original->_state);
2534
2535         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2536            the clone channel into the original channel.  Start by killing off the original
2537            channel's backend.   I'm not sure we're going to keep this function, because 
2538            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2539
2540         /* We need the clone's lock, too */
2541         ast_mutex_lock(&clone->lock);
2542
2543         ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2544
2545         /* Having remembered the original read/write formats, we turn off any translation on either
2546            one */
2547         free_translation(clone);
2548         free_translation(original);
2549
2550
2551         /* Unlink the masquerade */
2552         original->masq = NULL;
2553         clone->masqr = NULL;
2554         
2555         /* Save the original name */
2556         ast_copy_string(orig, original->name, sizeof(orig));
2557         /* Save the new name */
2558         ast_copy_string(newn, clone->name, sizeof(newn));
2559         /* Create the masq name */
2560         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2561                 
2562         /* Copy the name from the clone channel */
2563         ast_copy_string(original->name, newn, sizeof(original->name));
2564
2565         /* Mangle the name of the clone channel */
2566         ast_copy_string(clone->name, masqn, sizeof(clone->name));
2567         
2568         /* Notify any managers of the change, first the masq then the other */
2569         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2570         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2571
2572         /* Swap the technlogies */      
2573         t = original->tech;
2574         original->tech = clone->tech;
2575         clone->tech = t;
2576
2577         t_pvt = original->tech_pvt;
2578         original->tech_pvt = clone->tech_pvt;
2579         clone->tech_pvt = t_pvt;
2580
2581         /* Swap the readq's */
2582         cur = original->readq;
2583         original->readq = clone->readq;
2584         clone->readq = cur;
2585
2586         /* Swap the alertpipes */
2587         for (i = 0; i < 2; i++) {
2588                 x = original->alertpipe[i];
2589                 original->alertpipe[i] = clone->alertpipe[i];
2590                 clone->alertpipe[i] = x;
2591         }
2592
2593         /* Swap the raw formats */
2594         x = original->rawreadformat;
2595         original->rawreadformat = clone->rawreadformat;
2596         clone->rawreadformat = x;
2597         x = original->rawwriteformat;
2598         original->rawwriteformat = clone->rawwriteformat;
2599         clone->rawwriteformat = x;
2600
2601         /* Save any pending frames on both sides.  Start by counting
2602          * how many we're going to need... */
2603         prev = NULL;
2604         cur = clone->readq;
2605         x = 0;
2606         while(cur) {
2607                 x++;
2608                 prev = cur;
2609                 cur = cur->next;
2610         }
2611         /* If we had any, prepend them to the ones already in the queue, and 
2612          * load up the alertpipe */
2613         if (prev) {
2614                 prev->next = original->readq;
2615                 original->readq = clone->readq;
2616                 clone->readq = NULL;
2617                 if (original->alertpipe[1] > -1) {
2618                         for (i = 0; i < x; i++)
2619                                 write(original->alertpipe[1], &x, sizeof(x));
2620                 }
2621         }
2622         clone->_softhangup = AST_SOFTHANGUP_DEV;
2623
2624
2625         /* And of course, so does our current state.  Note we need not
2626            call ast_setstate since the event manager doesn't really consider
2627            these separate.  We do this early so that the clone has the proper
2628            state of the original channel. */
2629         origstate = original->_state;
2630         original->_state = clone->_state;
2631         clone->_state = origstate;
2632
2633         if (clone->tech->fixup){
2634                 res = clone->tech->fixup(original, clone);
2635                 if (res) 
2636                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2637         }
2638
2639         /* Start by disconnecting the original's physical side */
2640         if (clone->tech->hangup)
2641                 res = clone->tech->hangup(clone);
2642         if (res) {
2643                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2644                 ast_mutex_unlock(&clone->lock);
2645                 return -1;
2646         }
2647         
2648         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2649         /* Mangle the name of the clone channel */
2650         ast_copy_string(clone->name, zombn, sizeof(clone->name));
2651         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2652
2653         /* Update the type. */
2654         original->type = clone->type;
2655         
2656         /* Keep the same language.  */
2657         ast_copy_string(original->language, clone->language, sizeof(original->language));
2658         /* Copy the FD's */
2659         for (x = 0; x < AST_MAX_FDS; x++) {
2660                 original->fds[x] = clone->fds[x];
2661         }
2662         clone_variables(original, clone);
2663         clone->varshead.first = NULL;
2664         /* Presense of ADSI capable CPE follows clone */
2665         original->adsicpe = clone->adsicpe;
2666         /* Bridge remains the same */
2667         /* CDR fields remain the same */
2668         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2669         /* Application and data remain the same */
2670         /* Clone exception  becomes real one, as with fdno */
2671         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2672         original->fdno = clone->fdno;
2673         /* Schedule context remains the same */
2674         /* Stream stuff stays the same */
2675         /* Keep the original state.  The fixup code will need to work with it most likely */
2676
2677         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2678            out. */
2679         tmpcid = original->cid;
2680         original->cid = clone->cid;
2681         clone->cid = tmpcid;
2682         
2683         /* Restore original timing file descriptor */
2684         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2685         
2686         /* Our native formats are different now */
2687         original->nativeformats = clone->nativeformats;
2688         
2689         /* Context, extension, priority, app data, jump table,  remain the same */
2690         /* pvt switches.  pbx stays the same, as does next */
2691         
2692         /* Set the write format */
2693         ast_set_write_format(original, wformat);
2694
2695         /* Set the read format */
2696         ast_set_read_format(original, rformat);
2697
2698         /* Copy the music class */
2699         ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2700
2701         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2702
2703         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2704            can fix up everything as best as possible */
2705         if (original->tech->fixup) {
2706                 res = original->tech->fixup(clone, original);
2707                 if (res) {
2708                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
2709                                 original->type, original->name);
2710                         ast_mutex_unlock(&clone->lock);
2711                         return -1;
2712                 }
2713         } else
2714                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2715                         original->type, original->name);
2716         
2717         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2718            a zombie so nothing tries to touch it.  If it's already been marked as a
2719            zombie, then free it now (since it already is considered invalid). */
2720         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2721                 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
2722                 ast_mutex_unlock(&clone->lock);
2723                 ast_channel_free(clone);
2724                 manager_event(EVENT_FLAG_CALL, "Hangup", 
2725                         "Channel: %s\r\n"
2726                         "Uniqueid: %s\r\n"
2727                         "Cause: %d\r\n"
2728                         "Cause-txt: %s\r\n",
2729                         clone->name, 
2730                         clone->uniqueid, 
2731                         clone->hangupcause,
2732                         ast_cause2str(clone->hangupcause)
2733                         );
2734         } else {
2735                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2736                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2737                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2738                 ast_queue_frame(clone, &null_frame);
2739                 ast_mutex_unlock(&clone->lock);
2740         }
2741         
2742         /* Signal any blocker */
2743         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2744                 pthread_kill(original->blocker, SIGURG);
2745         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
2746         return 0;
2747 }
2748
2749 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2750 {
2751         if (callerid) {
2752                 if (chan->cid.cid_num)
2753                         free(chan->cid.cid_num);
2754                 if (ast_strlen_zero(callerid))
2755                         chan->cid.cid_num = NULL;
2756                 else
2757                         chan->cid.cid_num = strdup(callerid);
2758         }
2759         if (calleridname) {
2760                 if (chan->cid.cid_name)
2761                         free(chan->cid.cid_name);
2762                 if (ast_strlen_zero(calleridname))
2763                         chan->cid.cid_name = NULL;
2764                 else
2765                         chan->cid.cid_name = strdup(calleridname);
2766         }
2767         if (ani) {
2768                 if (chan->cid.cid_ani)
2769                         free(chan->cid.cid_ani);
2770                 if (ast_strlen_zero(ani))
2771                         chan->cid.cid_ani = NULL;
2772                 else
2773                         chan->cid.cid_ani = strdup(ani);
2774         }
2775         if (chan->cdr)
2776                 ast_cdr_setcid(chan->cdr, chan);
2777         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2778                                 "Channel: %s\r\n"
2779                                 "CallerID: %s\r\n"
2780                                 "CallerIDName: %s\r\n"
2781                                 "Uniqueid: %s\r\n"
2782                                 "CID-CallingPres: %d (%s)\r\n",
2783                                 chan->name, chan->cid.cid_num ? 
2784                                 chan->cid.cid_num : "<Unknown>",
2785                                 chan->cid.cid_name ? 
2786                                 chan->cid.cid_name : "<Unknown>",
2787                                 chan->uniqueid,
2788                                 chan->cid.cid_pres,
2789                                 ast_describe_caller_presentation(chan->cid.cid_pres)
2790                                 );
2791 }
2792
2793 int ast_setstate(struct ast_channel *chan, int state)
2794 {
2795         if (chan->_state != state) {
2796                 int oldstate = chan->_state;
2797                 chan->_state = state;
2798                 if (oldstate == AST_STATE_DOWN) {
2799                         ast_device_state_changed(chan->name);
2800                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2801                                 "Channel: %s\r\n"
2802                                 "State: %s\r\n"
2803                                 "CallerID: %s\r\n"
2804                                 "CallerIDName: %s\r\n"
2805                                 "Uniqueid: %s\r\n",
2806                                 chan->name, ast_state2str(chan->_state), 
2807                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2808                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2809                                 chan->uniqueid);
2810                 } else {
2811                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2812                                 "Channel: %s\r\n"
2813                                 "State: %s\r\n"
2814                                 "CallerID: %s\r\n"
2815                                 "CallerIDName: %s\r\n"
2816                                 "Uniqueid: %s\r\n",
2817                                 chan->name, ast_state2str(chan->_state), 
2818                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2819                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2820                                 chan->uniqueid);
2821                 }
2822         }
2823         return 0;
2824 }
2825
2826 /*--- Find bridged channel */
2827 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2828 {
2829         struct ast_channel *bridged;
2830         bridged = chan->_bridge;
2831         if (bridged && bridged->tech->bridged_channel) 
2832                 bridged = bridged->tech->bridged_channel(chan, bridged);
2833         return bridged;
2834 }
2835
2836 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2837 {
2838         int res=0, min=0, sec=0,check=0;
2839
2840         check = ast_autoservice_start(peer);
2841         if(check) 
2842                 return;
2843
2844         if (remain > 0) {
2845                 if (remain / 60 > 1) {
2846                         min = remain / 60;
2847                         sec = remain % 60;
2848                 } else {
2849                         sec = remain;
2850                 }
2851         }
2852         
2853         if (!strcmp(sound,"timeleft")) {        /* Queue support */
2854                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2855                 res = ast_waitstream(chan, "");
2856                 if (min) {
2857                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2858                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2859                         res = ast_waitstream(chan, "");
2860                 }
2861                 if (sec) {
2862                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2863                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2864                         res = ast_waitstream(chan, "");
2865                 }
2866         } else {
2867                 res = ast_streamfile(chan, sound, chan->language);
2868                 res = ast_waitstream(chan, "");
2869         }
2870
2871         check = ast_autoservice_stop(peer);
2872 }
2873
2874 static int ast_generic_bridge(int *playitagain, int *playit, struct timeval *start_time, struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2875 {
2876         /* Copy voice back and forth between the two channels.  Give the peer
2877            the ability to transfer calls with '#<extension' syntax. */
2878         struct ast_channel *cs[3];
2879         int to = -1;
2880         struct ast_frame *f;
2881         struct ast_channel *who = NULL;
2882         void *pvt0, *pvt1;
2883         int res=0;
2884         int o0nativeformats;
2885         int o1nativeformats;
2886         long elapsed_ms=0, time_left_ms=0;
2887         
2888         cs[0] = c0;
2889         cs[1] = c1;
2890         pvt0 = c0->pvt;
2891         pvt1 = c1->pvt;
2892         o0nativeformats = c0->nativeformats;
2893         o1nativeformats = c1->nativeformats;
2894
2895         for (;;) {
2896                 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) || (o0nativeformats != c0->nativeformats) ||
2897                         (o1nativeformats != c1->nativeformats)) {
2898                         /* Check for Masquerade, codec changes, etc */
2899                         res = -3;
2900                         break;
2901                 }
2902                 /* timestamp */
2903                 if (config->timelimit) {
2904                         /* If there is a time limit, return now */
2905                         elapsed_ms = ast_tvdiff_ms(ast_tvnow(), *start_time);
2906                         time_left_ms = config->timelimit - elapsed_ms;
2907
2908                         if (*playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) { 
2909                                 if (config->warning_freq == 0 || time_left_ms == config->play_warning || (time_left_ms % config->warning_freq) <= 50) {
2910                                         res = -3;
2911                                         break;
2912                                 }
2913                         }
2914                         if (time_left_ms <= 0) {
2915                                 res = -3;
2916                                 break;
2917                         }
2918                         if (time_left_ms >= 5000 && *playit) {
2919                                 res = -3;
2920                                 break;
2921                         }
2922                         
2923                 }
2924
2925                 who = ast_waitfor_n(cs, 2, &to);
2926                 if (!who) {
2927                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2928                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2929                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2930                                         c0->_softhangup = 0;
2931                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2932                                         c1->_softhangup = 0;
2933                                 c0->_bridge = c1;
2934                                 c1->_bridge = c0;
2935                                 continue;
2936                         }
2937                         continue;
2938                 }
2939                 f = ast_read(who);
2940                 if (!f) {
2941                         *fo = NULL;
2942                         *rc = who;
2943                         res = 0;
2944                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2945                         break;
2946                 }
2947
2948                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2949                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2950                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2951                         } else {
2952                                 *fo = f;
2953                                 *rc = who;
2954                                 res =  0;
2955                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2956                                 break;
2957                         }
2958                 }
2959                 if ((f->frametype == AST_FRAME_VOICE) ||
2960                         (f->frametype == AST_FRAME_TEXT) ||
2961                         (f->frametype == AST_FRAME_VIDEO) || 
2962                         (f->frametype == AST_FRAME_IMAGE) ||
2963                         (f->frametype == AST_FRAME_HTML) ||
2964                         (f->frametype == AST_FRAME_DTMF)) {
2965
2966                         if ((f->frametype == AST_FRAME_DTMF) && 
2967                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2968                                 if ((who == c0)) {
2969                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2970                                                 *rc = c0;
2971                                                 *fo = f;
2972                                                 /* Take out of conference mode */
2973                                                 res = 0;
2974                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2975                                                 break;
2976                                         } else 
2977                                                 goto tackygoto;
2978                                 } else
2979                                 if ((who == c1)) {
2980                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2981                                                 *rc = c1;
2982                                                 *fo = f;
2983                                                 res =  0;
2984                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2985                                                 break;
2986                                         } else
2987                                                 goto tackygoto;
2988                                 }
2989                         } else {
2990 #if 0
2991                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2992                                 if (who == last) 
2993                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2994                                 last = who;
2995 #endif
2996 tackygoto:
2997                                 /* Don't copy packets if there is a generator on either one, since they're
2998                                    not supposed to be listening anyway */
2999                                 if (who == c0) 
3000                                         ast_write(c1, f);
3001                                 else 
3002                                         ast_write(c0, f);
3003                         }
3004                 }
3005                 ast_frfree(f);
3006
3007                 /* Swap who gets priority */
3008                 cs[2] = cs[0];
3009                 cs[0] = cs[1];
3010                 cs[1] = cs[2];
3011         }
3012         return res;
3013 }
3014
3015 /*--- ast_channel_bridge: Bridge two channels together */
3016 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc) 
3017 {
3018         /* Copy voice back and forth between the two channels.  Give the peer
3019            the ability to transfer calls with '#<extension' syntax. */
3020         struct ast_channel *cs[3];
3021         struct ast_channel *who = NULL;
3022         int res=0;
3023         int nativefailed=0;
3024         int firstpass;
3025         int o0nativeformats;
3026         int o1nativeformats;
3027         struct timeval start_time;
3028         long elapsed_ms=0, time_left_ms=0;
3029         int playit=0, playitagain=1, first_time=1;
3030
3031         *fo = NULL;
3032         firstpass = config->firstpass;
3033         config->firstpass = 0;
3034
3035         /* timestamp */
3036         start_time = ast_tvnow();
3037         time_left_ms = config->timelimit;
3038
3039         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3040                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
3041         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
3042                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
3043
3044         /* Stop if we're a zombie or need a soft hangup */
3045         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) 
3046                 return -1;
3047         if (c0->_bridge) {
3048                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3049                         c0->name, c0->_bridge->name);
3050                 return -1;
3051         }
3052         if (c1->_bridge) {
3053                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3054                         c1->name, c1->_bridge->name);
3055                 return -1;
3056         }
3057         
3058         /* Keep track of bridge */
3059         c0->_bridge = c1;
3060         c1->_bridge = c0;
3061         cs[0] = c0;
3062         cs[1] = c1;
3063         
3064         manager_event(EVENT_FLAG_CALL, "Link", 
3065                         "Channel1: %s\r\n"
3066                         "Channel2: %s\r\n"
3067                         "Uniqueid1: %s\r\n"
3068                         "Uniqueid2: %s\r\n"
3069                         "CallerID1: %s\r\n"
3070                         "CallerID2: %s\r\n",
3071                         c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3072                                                                         
3073         o1nativeformats = c1->nativeformats;
3074         o0nativeformats = c0->nativeformats;
3075         for (/* ever */;;) {
3076                 /* timestamp */
3077                 if (config->timelimit) {
3078                         elapsed_ms = ast_tvdiff_ms(ast_tvnow(), start_time);
3079                         time_left_ms = config->timelimit - elapsed_ms;
3080
3081                         if (playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) { 
3082                                 /* narrowing down to the end */
3083                                 if (config->warning_freq == 0) {
3084                                         playit = 1;
3085                                         first_time=0;
3086                                         playitagain=0;
3087                                 } else if (first_time) {
3088                                         playit = 1;
3089                                         first_time=0;
3090                                 } else {
3091                                         if ((time_left_ms % config->warning_freq) <= 50) {
3092                                                 playit = 1;
3093                                         }
3094                                 }
3095                         }
3096                         if (time_left_ms <= 0) {
3097                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3098                                         bridge_playfile(c0,c1,config->end_sound,0);
3099                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3100                                         bridge_playfile(c1,c0,config->end_sound,0);
3101                                 *fo = NULL;
3102                                 if (who) 
3103                                         *rc = who;
3104                                 res = 0;
3105                                 break;
3106                         }
3107                         if (time_left_ms >= 5000 && playit) {
3108                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3109                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3110                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3111                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3112                                 playit = 0;
3113                         }
3114                         
3115                 }
3116
3117                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3118                &