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