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