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