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