Tue Mar 18 07:00:01 CET 2003
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
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 <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <signal.h>
20 #include <errno.h>
21 #include <unistd.h>
22 #include <math.h>                       /* For PI */
23 #include <asterisk/pbx.h>
24 #include <asterisk/frame.h>
25 #include <asterisk/sched.h>
26 #include <asterisk/options.h>
27 #include <asterisk/channel.h>
28 #include <asterisk/channel_pvt.h>
29 #include <asterisk/logger.h>
30 #include <asterisk/file.h>
31 #include <asterisk/translate.h>
32 #include <asterisk/manager.h>
33 #include <asterisk/chanvars.h>
34 #include <asterisk/linkedlists.h>
35 #include <asterisk/indications.h>
36
37
38 static int shutting_down = 0;
39
40 /* XXX Lock appropriately in more functions XXX */
41
42 #ifdef DEBUG_MUTEX
43 /* Convenient mutex debugging functions */
44 #define PTHREAD_MUTEX_LOCK(a) __PTHREAD_MUTEX_LOCK(__FUNCTION__, a)
45 #define PTHREAD_MUTEX_UNLOCK(a) __PTHREAD_MUTEX_UNLOCK(__FUNCTION__, a)
46
47 static int __PTHREAD_MUTEX_LOCK(char *f, pthread_mutex_t *a) {
48         ast_log(LOG_DEBUG, "Locking %p (%s)\n", a, f); 
49         return ast_pthread_mutex_lock(a);
50 }
51
52 static int __PTHREAD_MUTEX_UNLOCK(char *f, pthread_mutex_t *a) {
53         ast_log(LOG_DEBUG, "Unlocking %p (%s)\n", a, f); 
54         return ast_pthread_mutex_unlock(a);
55 }
56 #else
57 #define PTHREAD_MUTEX_LOCK(a) ast_pthread_mutex_lock(a)
58 #define PTHREAD_MUTEX_UNLOCK(a) ast_pthread_mutex_unlock(a)
59 #endif
60
61 struct chanlist {
62         char type[80];
63         char description[80];
64         int capabilities;
65         struct ast_channel * (*requester)(char *type, int format, void *data);
66         struct chanlist *next;
67 } *backends = NULL;
68 struct ast_channel *channels = NULL;
69
70 /* Protect the channel list (highly unlikely that two things would change
71    it at the same time, but still! */
72    
73 static pthread_mutex_t chlock = AST_MUTEX_INITIALIZER;
74
75 int ast_check_hangup(struct ast_channel *chan)
76 {
77 time_t  myt;
78
79           /* if soft hangup flag, return true */
80         if (chan->_softhangup) return 1;
81           /* if no private structure, return true */
82         if (!chan->pvt->pvt) return 1;
83           /* if no hangup scheduled, just return here */
84         if (!chan->whentohangup) return 0;
85         time(&myt); /* get current time */
86           /* return, if not yet */
87         if (chan->whentohangup > myt) return 0;
88         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
89         return 1;
90 }
91
92 void ast_begin_shutdown(int hangup)
93 {
94         struct ast_channel *c;
95         shutting_down = 1;
96         if (hangup) {
97                 PTHREAD_MUTEX_LOCK(&chlock);
98                 c = channels;
99                 while(c) {
100                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
101                         c = c->next;
102                 }
103                 PTHREAD_MUTEX_UNLOCK(&chlock);
104         }
105 }
106
107 int ast_active_channels(void)
108 {
109         struct ast_channel *c;
110         int cnt = 0;
111         PTHREAD_MUTEX_LOCK(&chlock);
112         c = channels;
113         while(c) {
114                 cnt++;
115                 c = c->next;
116         }
117         PTHREAD_MUTEX_UNLOCK(&chlock);
118         return cnt;
119 }
120
121 void ast_cancel_shutdown(void)
122 {
123         shutting_down = 0;
124 }
125
126 int ast_shutting_down(void)
127 {
128         return shutting_down;
129 }
130
131 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
132 {
133 time_t  myt;
134
135         time(&myt);
136         if (offset)
137           chan->whentohangup = myt + offset;
138         else
139           chan->whentohangup = 0;
140         return;
141 }
142
143 int ast_channel_register(char *type, char *description, int capabilities,
144                 struct ast_channel *(*requester)(char *type, int format, void *data))
145 {
146         struct chanlist *chan, *last=NULL;
147         if (PTHREAD_MUTEX_LOCK(&chlock)) {
148                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
149                 return -1;
150         }
151         chan = backends;
152         while(chan) {
153                 if (!strcasecmp(type, chan->type)) {
154                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
155                         PTHREAD_MUTEX_UNLOCK(&chlock);
156                         return -1;
157                 }
158                 last = chan;
159                 chan = chan->next;
160         }
161         chan = malloc(sizeof(struct chanlist));
162         if (!chan) {
163                 ast_log(LOG_WARNING, "Out of memory\n");
164                 PTHREAD_MUTEX_UNLOCK(&chlock);
165                 return -1;
166         }
167         strncpy(chan->type, type, sizeof(chan->type)-1);
168         strncpy(chan->description, description, sizeof(chan->description)-1);
169         chan->capabilities = capabilities;
170         chan->requester = requester;
171         chan->next = NULL;
172         if (last)
173                 last->next = chan;
174         else
175                 backends = chan;
176         if (option_debug)
177                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
178         else if (option_verbose > 1)
179                 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
180         PTHREAD_MUTEX_UNLOCK(&chlock);
181         return 0;
182 }
183
184 char *ast_state2str(int state)
185 {
186         switch(state) {
187         case AST_STATE_DOWN:
188                 return "Down";
189         case AST_STATE_RESERVED:
190                 return "Rsrvd";
191         case AST_STATE_OFFHOOK:
192                 return "OffHook";
193         case AST_STATE_DIALING:
194                 return "Dialing";
195         case AST_STATE_RING:
196                 return "Ring";
197         case AST_STATE_RINGING:
198                 return "Ringing";
199         case AST_STATE_UP:
200                 return "Up";
201         case AST_STATE_BUSY:
202                 return "Busy";
203         default:
204                 return "Unknown";
205         }
206 }
207
208
209 int ast_best_codec(int fmts)
210 {
211         /* This just our opinion, expressed in code.  We are asked to choose
212            the best codec to use, given no information */
213         int x;
214         static int prefs[] = 
215         {
216                 /* Okay, ulaw is used by all telephony equipment, so start with it */
217                 AST_FORMAT_ULAW,
218                 /* Unless of course, you're a silly European, so then prefer ALAW */
219                 AST_FORMAT_ALAW,
220                 /* Okay, well, signed linear is easy to translate into other stuff */
221                 AST_FORMAT_SLINEAR,
222                 /* ADPCM has great sound quality and is still pretty easy to translate */
223                 AST_FORMAT_ADPCM,
224                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
225                    translate and sounds pretty good */
226                 AST_FORMAT_GSM,
227                 /* Speex is free, but computationally more expensive than GSM */
228                 AST_FORMAT_SPEEX,
229                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
230                    to use it */
231                 AST_FORMAT_LPC10,
232                 /* G.729a is faster than 723 and slightly less expensive */
233                 AST_FORMAT_G729A,
234                 /* Down to G.723.1 which is proprietary but at least designed for voice */
235                 AST_FORMAT_G723_1,
236                 /* Last and least, MP3 which was of course never designed for real-time voice */
237                 AST_FORMAT_MP3,
238         };
239         
240         
241         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
242                 if (fmts & prefs[x])
243                         return prefs[x];
244         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
245         return 0;
246 }
247
248 struct ast_channel *ast_channel_alloc(int needqueue)
249 {
250         struct ast_channel *tmp;
251         struct ast_channel_pvt *pvt;
252         int x;
253         int flags;
254         struct varshead *headp;        
255                 
256         
257         /* If shutting down, don't allocate any new channels */
258         if (shutting_down)
259                 return NULL;
260         PTHREAD_MUTEX_LOCK(&chlock);
261         tmp = malloc(sizeof(struct ast_channel));
262         memset(tmp, 0, sizeof(struct ast_channel));
263         if (tmp) {
264                 pvt = malloc(sizeof(struct ast_channel_pvt));
265                 if (pvt) {
266                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
267                         tmp->sched = sched_context_create();
268                         if (tmp->sched) {
269                                 for (x=0;x<AST_MAX_FDS - 1;x++)
270                                         tmp->fds[x] = -1;
271                                 if (needqueue &&  
272                                         pipe(pvt->alertpipe)) {
273                                         ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
274                                         free(pvt);
275                                         free(tmp);
276                                         tmp = NULL;
277                                         pvt = NULL;
278                                 } else {
279                                         /* Make sure we've got it done right if they don't */
280                                         if (needqueue) {
281                                                 flags = fcntl(pvt->alertpipe[0], F_GETFL);
282                                                 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
283                                                 flags = fcntl(pvt->alertpipe[1], F_GETFL);
284                                                 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
285                                         } else
286                                                 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
287                                         /* Always watch the alertpipe */
288                                         tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
289                                         strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
290                                         tmp->pvt = pvt;
291                                         /* Initial state */
292                                         tmp->_state = AST_STATE_DOWN;
293                                         tmp->stack = -1;
294                                         tmp->streamid = -1;
295                                         tmp->appl = NULL;
296                                         tmp->data = NULL;
297                                         tmp->fin = 0;
298                                         tmp->fout = 0;
299                                         headp=&tmp->varshead;
300                                         ast_pthread_mutex_init(&tmp->lock);
301                                         AST_LIST_HEAD_INIT(headp);
302                                         tmp->vars=ast_var_assign("tempvar","tempval");
303                                         AST_LIST_INSERT_HEAD(headp,tmp->vars,entries);
304                                         strncpy(tmp->context, "default", sizeof(tmp->context)-1);
305                                         strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
306                                         strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
307                                         tmp->priority=1;
308                                         tmp->amaflags = ast_default_amaflags;
309                                         strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
310                                         tmp->next = channels;
311                                         channels= tmp;
312                                 }
313                         } else {
314                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
315                                 free(tmp);
316                                 tmp = NULL;
317                         }
318                 } else {
319                         ast_log(LOG_WARNING, "Out of memory\n");
320                         free(tmp);
321                         tmp = NULL;
322                 }
323         } else 
324                 ast_log(LOG_WARNING, "Out of memory\n");
325         PTHREAD_MUTEX_UNLOCK(&chlock);
326         return tmp;
327 }
328
329 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int lock)
330 {
331         struct ast_frame *f;
332         struct ast_frame *prev, *cur;
333         int blah = 1;
334         int qlen = 0;
335         /* Build us a copy and free the original one */
336         f = ast_frdup(fin);
337         if (!f) {
338                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
339                 return -1;
340         }
341         if (lock)
342                 ast_pthread_mutex_lock(&chan->lock);
343         prev = NULL;
344         cur = chan->pvt->readq;
345         while(cur) {
346                 prev = cur;
347                 cur = cur->next;
348                 qlen++;
349         }
350         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
351         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
352                 if (fin->frametype != AST_FRAME_VOICE) {
353                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
354                         CRASH;
355                 } else {
356                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
357                         ast_frfree(fin);
358                         if (lock)
359                                 ast_pthread_mutex_unlock(&chan->lock);
360                         return 0;
361                 }
362         }
363         if (prev)
364                 prev->next = f;
365         else
366                 chan->pvt->readq = f;
367         if (chan->pvt->alertpipe[1] > -1) {
368                 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
369                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
370                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
371         }
372         if (lock)
373                 ast_pthread_mutex_unlock(&chan->lock);
374         return 0;
375 }
376
377 int ast_queue_hangup(struct ast_channel *chan, int lock)
378 {
379         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
380         chan->_softhangup |= AST_SOFTHANGUP_DEV;
381         return ast_queue_frame(chan, &f, lock);
382 }
383
384 int ast_queue_control(struct ast_channel *chan, int control, int lock)
385 {
386         struct ast_frame f = { AST_FRAME_CONTROL, };
387         f.subclass = control;
388         return ast_queue_frame(chan, &f, lock);
389 }
390
391 int ast_channel_defer_dtmf(struct ast_channel *chan)
392 {
393         int pre = 0;
394         if (chan) {
395                 pre = chan->deferdtmf;
396                 chan->deferdtmf = 1;
397         }
398         return pre;
399 }
400
401 void ast_channel_undefer_dtmf(struct ast_channel *chan)
402 {
403         if (chan)
404                 chan->deferdtmf = 0;
405 }
406
407 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
408 {
409         struct ast_channel *l, *ret=NULL;
410         PTHREAD_MUTEX_LOCK(&chlock);
411         l = channels;
412         if (!prev) {
413                 PTHREAD_MUTEX_UNLOCK(&chlock);
414                 return l;
415         }
416         while(l) {
417                 if (l == prev)
418                         ret = l->next;
419                 l = l->next;
420         }
421         PTHREAD_MUTEX_UNLOCK(&chlock);
422         return ret;
423         
424 }
425
426 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
427                                                                 int (*cond)(void*), void *data )
428 {
429         struct ast_frame *f;
430
431         while(ms > 0) {
432                 if( cond && ((*cond)(data) == 0 ) )
433                         return 0;
434                 ms = ast_waitfor(chan, ms);
435                 if (ms <0)
436                         return -1;
437                 if (ms > 0) {
438                         f = ast_read(chan);
439                         if (!f)
440                                 return -1;
441                         ast_frfree(f);
442                 }
443         }
444         return 0;
445 }
446
447 int ast_safe_sleep(struct ast_channel *chan, int ms)
448 {
449         struct ast_frame *f;
450         while(ms > 0) {
451                 ms = ast_waitfor(chan, ms);
452                 if (ms <0)
453                         return -1;
454                 if (ms > 0) {
455                         f = ast_read(chan);
456                         if (!f)
457                                 return -1;
458                         ast_frfree(f);
459                 }
460         }
461         return 0;
462 }
463
464 void ast_channel_free(struct ast_channel *chan)
465 {
466         struct ast_channel *last=NULL, *cur;
467         int fd;
468         struct ast_var_t *vardata;
469         struct ast_frame *f, *fp;
470         struct varshead *headp;
471         
472         headp=&chan->varshead;
473         
474         PTHREAD_MUTEX_LOCK(&chlock);
475         cur = channels;
476         while(cur) {
477                 if (cur == chan) {
478                         if (last)
479                                 last->next = cur->next;
480                         else
481                                 channels = cur->next;
482                         break;
483                 }
484                 last = cur;
485                 cur = cur->next;
486         }
487         if (!cur)
488                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
489         if (chan->pvt->pvt)
490                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
491         /* Free translatosr */
492         if (chan->pvt->readtrans)
493                 ast_translator_free_path(chan->pvt->readtrans);
494         if (chan->pvt->writetrans)
495                 ast_translator_free_path(chan->pvt->writetrans);
496         if (chan->pbx) 
497                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
498         if (chan->dnid)
499                 free(chan->dnid);
500         if (chan->callerid)
501                 free(chan->callerid);   
502         if (chan->ani)
503                 free(chan->ani);
504         if (chan->rdnis)
505                 free(chan->rdnis);
506         pthread_mutex_destroy(&chan->lock);
507         /* Close pipes if appropriate */
508         if ((fd = chan->pvt->alertpipe[0]) > -1)
509                 close(fd);
510         if ((fd = chan->pvt->alertpipe[1]) > -1)
511                 close(fd);
512         f = chan->pvt->readq;
513         chan->pvt->readq = NULL;
514         while(f) {
515                 fp = f;
516                 f = f->next;
517                 ast_frfree(fp);
518         }
519         
520         /* loop over the variables list, freeing all data and deleting list items */
521         /* no need to lock the list, as the channel is already locked */
522         
523         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
524                     vardata = AST_LIST_FIRST(headp);
525                     AST_LIST_REMOVE_HEAD(headp, entries);
526 //                  printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata));
527                     ast_var_delete(vardata);
528         }
529                                                          
530
531         free(chan->pvt);
532         chan->pvt = NULL;
533         free(chan);
534         PTHREAD_MUTEX_UNLOCK(&chlock);
535 }
536
537 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
538 {
539         int res = 0;
540         struct ast_frame f = { AST_FRAME_NULL };
541         if (option_debug)
542                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
543         /* Inform channel driver that we need to be hung up, if it cares */
544         chan->_softhangup |= cause;
545         ast_queue_frame(chan, &f, 0);
546         /* Interrupt any select call or such */
547         if (chan->blocking)
548                 pthread_kill(chan->blocker, SIGURG);
549         return res;
550 }
551
552 int ast_softhangup(struct ast_channel *chan, int cause)
553 {
554         int res;
555         ast_pthread_mutex_lock(&chan->lock);
556         res = ast_softhangup_nolock(chan, cause);
557         ast_pthread_mutex_unlock(&chan->lock);
558         return res;
559 }
560
561 static int ast_do_masquerade(struct ast_channel *original);
562
563 static void free_translation(struct ast_channel *clone)
564 {
565         if (clone->pvt->writetrans)
566                 ast_translator_free_path(clone->pvt->writetrans);
567         if (clone->pvt->readtrans)
568                 ast_translator_free_path(clone->pvt->readtrans);
569         clone->pvt->writetrans = NULL;
570         clone->pvt->readtrans = NULL;
571         clone->pvt->rawwriteformat = clone->nativeformats;
572         clone->pvt->rawreadformat = clone->nativeformats;
573 }
574
575 int ast_hangup(struct ast_channel *chan)
576 {
577         int res = 0;
578         /* Don't actually hang up a channel that will masquerade as someone else, or
579            if someone is going to masquerade as us */
580         ast_pthread_mutex_lock(&chan->lock);
581         if (chan->masq) {
582                 if (ast_do_masquerade(chan)) 
583                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
584         }
585
586         if (chan->masq) {
587                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
588                 ast_pthread_mutex_unlock(&chan->lock);
589                 return 0;
590         }
591         /* If this channel is one which will be masqueraded into something, 
592            mark it as a zombie already, so we know to free it later */
593         if (chan->masqr) {
594                 ast_pthread_mutex_unlock(&chan->lock);
595                 chan->zombie=1;
596                 return 0;
597         }
598         free_translation(chan);
599         if (chan->stream)
600                 ast_stopstream(chan);
601         if (chan->sched)
602                 sched_context_destroy(chan->sched);
603         /* Clear any tone stuff remaining */
604         if (chan->generatordata)
605                 chan->generator->release(chan, chan->generatordata);
606         chan->generatordata = NULL;
607         chan->generator = NULL;
608         if (chan->cdr) {
609                 /* End the CDR if it hasn't already */
610                 ast_cdr_end(chan->cdr);
611                 /* Post and Free the CDR */
612                 ast_cdr_post(chan->cdr);
613                 ast_cdr_free(chan->cdr);
614         }
615         if (chan->blocking) {
616                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
617                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
618                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
619                 CRASH;
620         }
621         if (!chan->zombie) {
622                 if (option_debug)
623                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
624                 if (chan->pvt->hangup)
625                         res = chan->pvt->hangup(chan);
626         } else
627                 if (option_debug)
628                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
629                         
630         ast_pthread_mutex_unlock(&chan->lock);
631         manager_event(EVENT_FLAG_CALL, "Hangup", 
632                         "Channel: %s\r\n",
633                         chan->name);
634         ast_channel_free(chan);
635         return res;
636 }
637
638 void ast_channel_unregister(char *type)
639 {
640         struct chanlist *chan, *last=NULL;
641         if (option_debug)
642                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
643         if (PTHREAD_MUTEX_LOCK(&chlock)) {
644                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
645                 return;
646         }
647         chan = backends;
648         while(chan) {
649                 if (!strcasecmp(chan->type, type)) {
650                         if (last)
651                                 last->next = chan->next;
652                         else
653                                 backends = backends->next;
654                         free(chan);
655                         PTHREAD_MUTEX_UNLOCK(&chlock);
656                         return;
657                 }
658                 last = chan;
659                 chan = chan->next;
660         }
661         PTHREAD_MUTEX_UNLOCK(&chlock);
662 }
663
664 int ast_answer(struct ast_channel *chan)
665 {
666         int res = 0;
667         /* Stop if we're a zombie or need a soft hangup */
668         if (chan->zombie || ast_check_hangup(chan)) 
669                 return -1;
670         switch(chan->_state) {
671         case AST_STATE_RINGING:
672         case AST_STATE_RING:
673                 if (chan->pvt->answer)
674                         res = chan->pvt->answer(chan);
675                 ast_setstate(chan, AST_STATE_UP);
676                 if (chan->cdr)
677                         ast_cdr_answer(chan->cdr);
678                 return res;
679                 break;
680         case AST_STATE_UP:
681                 if (chan->cdr)
682                         ast_cdr_answer(chan->cdr);
683                 break;
684         }
685         return 0;
686 }
687
688 void ast_deactivate_generator(struct ast_channel *chan)
689 {
690         if (chan->generatordata) {
691                 chan->generator->release(chan, chan->generatordata);
692                 chan->generatordata = NULL;
693                 chan->generator = NULL;
694                 chan->writeinterrupt = 0;
695         }
696 }
697
698 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
699 {
700         if (chan->generatordata) {
701                 chan->generator->release(chan, chan->generatordata);
702                 chan->generatordata = NULL;
703         }
704         if ((chan->generatordata = gen->alloc(chan, params))) {
705                 chan->generator = gen;
706         } else {
707                 return -1;
708         }
709         return 0;
710 }
711
712 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
713 {
714         /* Wait for x amount of time on a file descriptor to have input.  */
715         struct timeval tv;
716         fd_set rfds, efds;
717         int res;
718         int x, max=-1;
719         int winner = -1;
720         
721         tv.tv_sec = *ms / 1000;
722         tv.tv_usec = (*ms % 1000) * 1000;
723         FD_ZERO(&rfds);
724         FD_ZERO(&efds);
725         for (x=0;x<n;x++) {
726                 if (fds[x] > -1) {
727                         FD_SET(fds[x], &rfds);
728                         FD_SET(fds[x], &efds);
729                         if (fds[x] > max)
730                                 max = fds[x];
731                 }
732         }
733         if (*ms >= 0) 
734                 res = select(max + 1, &rfds, NULL, &efds, &tv);
735         else
736                 res = select(max + 1, &rfds, NULL, &efds, NULL);
737
738         if (res < 0) {
739                 /* Simulate a timeout if we were interrupted */
740                 if (errno != EINTR)
741                         *ms = -1;
742                 else
743                         *ms = 0;
744                 return -1;
745         }
746
747         for (x=0;x<n;x++) {
748                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
749                         if (exception)
750                                 *exception = FD_ISSET(fds[x], &efds);
751                         winner = fds[x];
752                 }
753         }
754         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
755         return winner;
756 }
757
758 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
759         int *exception, int *outfd, int *ms)
760 {
761         /* Wait for x amount of time on a file descriptor to have input.  */
762         struct timeval tv;
763         fd_set rfds, efds;
764         int res;
765         int x, y, max=-1;
766         struct ast_channel *winner = NULL;
767         if (outfd)
768                 *outfd = -1;
769         if (exception)
770                 *exception = 0;
771         
772         /* Perform any pending masquerades */
773         for (x=0;x<n;x++) {
774                 if (c[x]->masq) {
775                         if (ast_do_masquerade(c[x])) {
776                                 ast_log(LOG_WARNING, "Masquerade failed\n");
777                                 *ms = -1;
778                                 return NULL;
779                         }
780                 }
781         }
782         
783         tv.tv_sec = *ms / 1000;
784         tv.tv_usec = (*ms % 1000) * 1000;
785         FD_ZERO(&rfds);
786         FD_ZERO(&efds);
787
788         for (x=0;x<n;x++) {
789                 for (y=0;y<AST_MAX_FDS;y++) {
790                         if (c[x]->fds[y] > -1) {
791                                 FD_SET(c[x]->fds[y], &rfds);
792                                 FD_SET(c[x]->fds[y], &efds);
793                                 if (c[x]->fds[y] > max)
794                                         max = c[x]->fds[y];
795                         }
796                 }
797                 CHECK_BLOCKING(c[x]);
798         }
799         for (x=0;x<nfds; x++) {
800                 FD_SET(fds[x], &rfds);
801                 FD_SET(fds[x], &efds);
802                 if (fds[x] > max)
803                         max = fds[x];
804         }
805         if (*ms >= 0) 
806                 res = select(max + 1, &rfds, NULL, &efds, &tv);
807         else
808                 res = select(max + 1, &rfds, NULL, &efds, NULL);
809
810         if (res < 0) {
811                 for (x=0;x<n;x++) 
812                         c[x]->blocking = 0;
813                 /* Simulate a timeout if we were interrupted */
814                 if (errno != EINTR)
815                         *ms = -1;
816                 else {
817                         /* Just an interrupt */
818 #if 0
819                         *ms = 0;
820 #endif                  
821                 }
822                 return NULL;
823         }
824
825         for (x=0;x<n;x++) {
826                 c[x]->blocking = 0;
827                 for (y=0;y<AST_MAX_FDS;y++) {
828                         if (c[x]->fds[y] > -1) {
829                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
830                                         /* Set exception flag if appropriate */
831                                         if (FD_ISSET(c[x]->fds[y], &efds))
832                                                 c[x]->exception = 1;
833                                         c[x]->fdno = y;
834                                         winner = c[x];
835                                 }
836                         }
837                 }
838         }
839         for (x=0;x<nfds;x++) {
840                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
841                         if (outfd)
842                                 *outfd = fds[x];
843                         if (FD_ISSET(fds[x], &efds) && exception)
844                                 *exception = 1;
845                         winner = NULL;
846                 }
847         }
848         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
849         return winner;
850 }
851
852 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
853 {
854         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
855 }
856
857 int ast_waitfor(struct ast_channel *c, int ms)
858 {
859         struct ast_channel *chan;
860         int oldms = ms;
861         chan = ast_waitfor_n(&c, 1, &ms);
862         if (ms < 0) {
863                 if (oldms < 0)
864                         return 0;
865                 else
866                         return -1;
867         }
868         return ms;
869 }
870
871 char ast_waitfordigit(struct ast_channel *c, int ms)
872 {
873         /* XXX Should I be merged with waitfordigit_full XXX */
874         struct ast_frame *f;
875         char result = 0;
876         /* Stop if we're a zombie or need a soft hangup */
877         if (c->zombie || ast_check_hangup(c)) 
878                 return -1;
879         /* Wait for a digit, no more than ms milliseconds total. */
880         while(ms && !result) {
881                 ms = ast_waitfor(c, ms);
882                 if (ms < 0) /* Error */
883                         result = -1; 
884                 else if (ms > 0) {
885                         /* Read something */
886                         f = ast_read(c);
887                         if (f) {
888                                 if (f->frametype == AST_FRAME_DTMF) 
889                                         result = f->subclass;
890                                 ast_frfree(f);
891                         } else
892                                 result = -1;
893                 }
894         }
895         return result;
896 }
897
898 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
899 {
900         struct ast_frame *f;
901         char result = 0;
902         struct ast_channel *rchan;
903         int outfd;
904         /* Stop if we're a zombie or need a soft hangup */
905         if (c->zombie || ast_check_hangup(c)) 
906                 return -1;
907         /* Wait for a digit, no more than ms milliseconds total. */
908         while(ms && !result) {
909                 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
910                 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
911                         result = -1; 
912                 else if (outfd > -1) {
913                         result = 1;
914                 } else if (rchan) {
915                         /* Read something */
916                         f = ast_read(c);
917                         if (f) {
918                                 if (f->frametype == AST_FRAME_DTMF) 
919                                         result = f->subclass;
920                                 ast_frfree(f);
921                         } else
922                                 result = -1;
923                 }
924         }
925         return result;
926 }
927
928 struct ast_frame *ast_read(struct ast_channel *chan)
929 {
930         struct ast_frame *f = NULL;
931         int blah;
932         static struct ast_frame null_frame = 
933         {
934                 AST_FRAME_NULL,
935         };
936         
937         ast_pthread_mutex_lock(&chan->lock);
938         if (chan->masq) {
939                 if (ast_do_masquerade(chan)) {
940                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
941                         f = NULL;
942                 } else
943                         f =  &null_frame;
944                 pthread_mutex_unlock(&chan->lock);
945                 return f;
946         }
947
948         /* Stop if we're a zombie or need a soft hangup */
949         if (chan->zombie || ast_check_hangup(chan)) {
950                 if (chan->generator)
951                         ast_deactivate_generator(chan);
952                 pthread_mutex_unlock(&chan->lock);
953                 return NULL;
954         }
955
956         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
957                 /* We have DTMF that has been deferred.  Return it now */
958                 chan->dtmff.frametype = AST_FRAME_DTMF;
959                 chan->dtmff.subclass = chan->dtmfq[0];
960                 /* Drop first digit */
961                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
962                 pthread_mutex_unlock(&chan->lock);
963                 return &chan->dtmff;
964         }
965         
966         /* Read and ignore anything on the alertpipe, but read only
967            one sizeof(blah) per frame that we send from it */
968         if (chan->pvt->alertpipe[0] > -1) {
969                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
970         }
971
972         /* Check for pending read queue */
973         if (chan->pvt->readq) {
974                 f = chan->pvt->readq;
975                 chan->pvt->readq = f->next;
976                 /* Interpret hangup and return NULL */
977                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
978                         f = NULL;
979         } else {
980                 chan->blocker = pthread_self();
981                 if (chan->exception) {
982                         if (chan->pvt->exception) 
983                                 f = chan->pvt->exception(chan);
984                         else {
985                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
986                                 f = &null_frame;
987                         }
988                         /* Clear the exception flag */
989                         chan->exception = 0;
990                 } else
991                 if (chan->pvt->read)
992                         f = chan->pvt->read(chan);
993                 else
994                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
995         }
996
997
998         if (f && (f->frametype == AST_FRAME_VOICE)) {
999                 if (!(f->subclass & chan->nativeformats)) {
1000                         /* This frame can't be from the current native formats -- drop it on the
1001                            floor */
1002                         ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %d since our native format has changed to %d\n", chan->name, f->subclass, chan->nativeformats);
1003                         ast_frfree(f);
1004                         f = &null_frame;
1005                 } else if (chan->pvt->readtrans) {
1006                         f = ast_translate(chan->pvt->readtrans, f, 1);
1007                         if (!f)
1008                                 f = &null_frame;
1009                 }
1010         }
1011
1012         /* Make sure we always return NULL in the future */
1013         if (!f) {
1014                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1015                 if (chan->generator)
1016                         ast_deactivate_generator(chan);
1017                 /* End the CDR if appropriate */
1018                 if (chan->cdr)
1019                         ast_cdr_end(chan->cdr);
1020         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1021                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1022                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1023                 else
1024                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1025                 f = &null_frame;
1026         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1027                 /* Answer the CDR */
1028                 ast_setstate(chan, AST_STATE_UP);
1029                 ast_cdr_answer(chan->cdr);
1030         }
1031         pthread_mutex_unlock(&chan->lock);
1032
1033         /* Run any generator sitting on the line */
1034         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1035                 /* Mask generator data temporarily */
1036                 void *tmp;
1037                 int res;
1038                 tmp = chan->generatordata;
1039                 chan->generatordata = NULL;
1040                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1041                 chan->generatordata = tmp;
1042                 if (res) {
1043                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1044                         ast_deactivate_generator(chan);
1045                 }
1046         }
1047         if (chan->fin & 0x80000000)
1048                 ast_frame_dump(chan->name, f, "<<");
1049         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1050                 chan->fin &= 0x80000000;
1051         else
1052                 chan->fin++;
1053         return f;
1054 }
1055
1056 int ast_indicate(struct ast_channel *chan, int condition)
1057 {
1058         int res = -1;
1059         /* Stop if we're a zombie or need a soft hangup */
1060         if (chan->zombie || ast_check_hangup(chan)) 
1061                 return -1;
1062         if (chan->pvt->indicate)
1063                 res = chan->pvt->indicate(chan, condition);
1064         if (!chan->pvt->indicate || res) {
1065                 /*
1066                  * Device does not support (that) indication, lets fake
1067                  * it by doing our own tone generation. (PM2002)
1068                  */
1069                 if (condition >= 0) {
1070                         const struct tone_zone_sound *ts = NULL;
1071                         switch (condition) {
1072                          case AST_CONTROL_RINGING:
1073                                 ts = ast_get_indication_tone(chan->zone, "ring");
1074                                 break;
1075                          case AST_CONTROL_BUSY:
1076                                 ts = ast_get_indication_tone(chan->zone, "busy");
1077                                 break;
1078                          case AST_CONTROL_CONGESTION:
1079                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1080                                 break;
1081                         }
1082                         if (ts && ts->data[0]) {
1083                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1084                                 ast_playtones_start(chan,0,ts->data, 1);
1085                         }
1086                         else  {
1087                                 /* not handled */
1088                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1089                                 return -1;
1090                         }
1091                 }
1092                 else ast_playtones_stop(chan);
1093         }
1094         return 0;
1095 }
1096
1097 int ast_recvchar(struct ast_channel *chan, int timeout)
1098 {
1099         int res,ourto,c;
1100         struct ast_frame *f;
1101         
1102         ourto = timeout;
1103         for(;;)
1104            {
1105                 if (ast_check_hangup(chan)) return -1;
1106                 res = ast_waitfor(chan,ourto);
1107                 if (res <= 0) /* if timeout */
1108                    {
1109                         return 0;
1110                    }
1111                 ourto = res;
1112                 f = ast_read(chan);
1113                 if (f == NULL) return -1; /* if hangup */
1114                 if ((f->frametype == AST_FRAME_CONTROL) &&
1115                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1116                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1117                    {
1118                         c = *((char *)f->data);  /* get the data */
1119                         ast_frfree(f);
1120                         return(c);
1121                    }
1122                 ast_frfree(f);
1123         }
1124 }
1125
1126 int ast_sendtext(struct ast_channel *chan, char *text)
1127 {
1128         int res = 0;
1129         /* Stop if we're a zombie or need a soft hangup */
1130         if (chan->zombie || ast_check_hangup(chan)) 
1131                 return -1;
1132         CHECK_BLOCKING(chan);
1133         if (chan->pvt->send_text)
1134                 res = chan->pvt->send_text(chan, text);
1135         chan->blocking = 0;
1136         return res;
1137 }
1138
1139 static int do_senddigit(struct ast_channel *chan, char digit)
1140 {
1141         int res = -1;
1142
1143         if (chan->pvt->send_digit)
1144                 res = chan->pvt->send_digit(chan, digit);
1145         if (!chan->pvt->send_digit || res) {
1146                 /*
1147                  * Device does not support DTMF tones, lets fake
1148                  * it by doing our own generation. (PM2002)
1149                  */
1150                 static const char* dtmf_tones[] = {
1151                         "!941+1336/50,!0/50",   /* 0 */
1152                         "!697+1209/50,!0/50",   /* 1 */
1153                         "!697+1336/50,!0/50",   /* 2 */
1154                         "!697+1477/50,!0/50",   /* 3 */
1155                         "!770+1209/50,!0/50",   /* 4 */
1156                         "!770+1336/50,!0/50",   /* 5 */
1157                         "!770+1477/50,!0/50",   /* 6 */
1158                         "!852+1209/50,!0/50",   /* 7 */
1159                         "!852+1336/50,!0/50",   /* 8 */
1160                         "!852+1477/50,!0/50",   /* 9 */
1161                         "!697+1633/50,!0/50",   /* A */
1162                         "!770+1633/50,!0/50",   /* B */
1163                         "!852+1633/50,!0/50",   /* C */
1164                         "!941+1633/50,!0/50",   /* D */
1165                         "!941+1209/50,!0/50",   /* * */
1166                         "!941+1477/50,!0/50" }; /* # */
1167                 if (digit >= '0' && digit <='9')
1168                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1169                 else if (digit >= 'A' && digit <= 'D')
1170                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1171                 else if (digit == '*')
1172                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1173                 else if (digit == '#')
1174                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1175                 else {
1176                         /* not handled */
1177                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1178                         return -1;
1179                 }
1180         }
1181         return 0;
1182 }
1183
1184 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1185 {
1186         int res = -1;
1187         struct ast_frame *f = NULL;
1188         /* Stop if we're a zombie or need a soft hangup */
1189         if (chan->zombie || ast_check_hangup(chan)) 
1190                 return -1;
1191         /* Handle any pending masquerades */
1192         if (chan->masq) {
1193                 if (ast_do_masquerade(chan)) {
1194                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1195                         return -1;
1196                 }
1197         }
1198         if (chan->masqr)
1199                 return 0;
1200         if (chan->generatordata) {
1201                 if (chan->writeinterrupt)
1202                         ast_deactivate_generator(chan);
1203                 else
1204                         return 0;
1205         }
1206         if (chan->fout & 0x80000000)
1207                 ast_frame_dump(chan->name, fr, ">>");
1208         CHECK_BLOCKING(chan);
1209         switch(fr->frametype) {
1210         case AST_FRAME_CONTROL:
1211                 /* XXX Interpret control frames XXX */
1212                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1213                 break;
1214         case AST_FRAME_DTMF:
1215                 res = do_senddigit(chan,fr->subclass);
1216                 break;
1217         case AST_FRAME_TEXT:
1218                 if (chan->pvt->send_text)
1219                         res = chan->pvt->send_text(chan, (char *) fr->data);
1220                 break;
1221         default:
1222                 if (chan->pvt->write) {
1223                         if (chan->pvt->writetrans) {
1224                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1225                         } else
1226                                 f = fr;
1227                         if (f)  
1228                                 res = chan->pvt->write(chan, f);
1229                         else
1230                                 res = 0;
1231                 }
1232         }
1233         if (f && (f != fr))
1234                 ast_frfree(f);
1235         chan->blocking = 0;
1236         /* Consider a write failure to force a soft hangup */
1237         if (res < 0)
1238                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1239         else {
1240                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1241                         chan->fout &= 0x80000000;
1242                 else
1243                         chan->fout++;
1244                 chan->fout++;
1245         }
1246         return res;
1247 }
1248
1249 int ast_set_write_format(struct ast_channel *chan, int fmts)
1250 {
1251         int fmt;
1252         int native;
1253         int res;
1254         
1255         native = chan->nativeformats;
1256         fmt = fmts;
1257         
1258         res = ast_translator_best_choice(&native, &fmt);
1259         if (res < 0) {
1260                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1261                 return -1;
1262         }
1263         
1264         /* Now we have a good choice for both.  We'll write using our native format. */
1265         chan->pvt->rawwriteformat = native;
1266         /* User perspective is fmt */
1267         chan->writeformat = fmt;
1268         /* Free any write translation we have right now */
1269         if (chan->pvt->writetrans)
1270                 ast_translator_free_path(chan->pvt->writetrans);
1271         /* Build a translation path from the user write format to the raw writing format */
1272         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1273         if (option_debug)
1274                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1275         return 0;
1276 }
1277
1278 int ast_set_read_format(struct ast_channel *chan, int fmts)
1279 {
1280         int fmt;
1281         int native;
1282         int res;
1283         
1284         native = chan->nativeformats;
1285         fmt = fmts;
1286         /* Find a translation path from the native read format to one of the user's read formats */
1287         res = ast_translator_best_choice(&fmt, &native);
1288         if (res < 0) {
1289                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1290                 return -1;
1291         }
1292         
1293         /* Now we have a good choice for both.  We'll write using our native format. */
1294         chan->pvt->rawreadformat = native;
1295         /* User perspective is fmt */
1296         chan->readformat = fmt;
1297         /* Free any read translation we have right now */
1298         if (chan->pvt->readtrans)
1299                 ast_translator_free_path(chan->pvt->readtrans);
1300         /* Build a translation path from the raw read format to the user reading format */
1301         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1302         if (option_debug)
1303                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1304         return 0;
1305 }
1306
1307 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1308 {
1309         int state = 0;
1310         struct ast_channel *chan;
1311         struct ast_frame *f;
1312         int res;
1313         
1314         chan = ast_request(type, format, data);
1315         if (chan) {
1316                 if (callerid)
1317                         ast_set_callerid(chan, callerid, 1);
1318                 if (!ast_call(chan, data, 0)) {
1319                         while(timeout && (chan->_state != AST_STATE_UP)) {
1320                                 res = ast_waitfor(chan, timeout);
1321                                 if (res < 0) {
1322                                         /* Something not cool, or timed out */
1323                                         ast_hangup(chan);
1324                                         chan = NULL;
1325                                         break;
1326                                 }
1327                                 /* If done, break out */
1328                                 if (!res)
1329                                         break;
1330                                 if (timeout > -1)
1331                                         timeout = res;
1332                                 f = ast_read(chan);
1333                                 if (!f) {
1334                                         state = AST_CONTROL_HANGUP;
1335                                         ast_hangup(chan);
1336                                         chan = NULL;
1337                                         break;
1338                                 }
1339                                 if (f->frametype == AST_FRAME_CONTROL) {
1340                                         if (f->subclass == AST_CONTROL_RINGING)
1341                                                 state = AST_CONTROL_RINGING;
1342                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1343                                                 state = f->subclass;
1344                                                 break;
1345                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1346                                                 state = f->subclass;
1347                                                 break;
1348                                         } else {
1349                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1350                                         }
1351                                 }
1352                                 ast_frfree(f);
1353                         }
1354                 } else {
1355                         ast_hangup(chan);
1356                         chan = NULL;
1357                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1358                 }
1359         } else
1360                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1361         if (chan && (chan->_state == AST_STATE_UP))
1362                 state = AST_CONTROL_ANSWER;
1363         if (outstate)
1364                 *outstate = state;
1365         return chan;
1366 }
1367
1368 struct ast_channel *ast_request(char *type, int format, void *data)
1369 {
1370         struct chanlist *chan;
1371         struct ast_channel *c = NULL;
1372         int capabilities;
1373         int fmt;
1374         int res;
1375         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1376                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1377                 return NULL;
1378         }
1379         chan = backends;
1380         while(chan) {
1381                 if (!strcasecmp(type, chan->type)) {
1382                         capabilities = chan->capabilities;
1383                         fmt = format;
1384                         res = ast_translator_best_choice(&fmt, &capabilities);
1385                         if (res < 0) {
1386                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1387                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1388                                 return NULL;
1389                         }
1390                         PTHREAD_MUTEX_UNLOCK(&chlock);
1391                         if (chan->requester)
1392                                 c = chan->requester(type, capabilities, data);
1393                         if (c) {
1394                                 manager_event(EVENT_FLAG_CALL, "Newchannel",
1395                                 "Channel: %s\r\n"
1396                                 "State: %s\r\n"
1397                                 "Callerid: %s\r\n",
1398                                 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>");
1399                         }
1400                         return c;
1401                 }
1402                 chan = chan->next;
1403         }
1404         if (!chan)
1405                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1406         PTHREAD_MUTEX_UNLOCK(&chlock);
1407         return c;
1408 }
1409
1410 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1411 {
1412         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1413            If the remote end does not answer within the timeout, then do NOT hang up, but 
1414            return anyway.  */
1415         int res = -1;
1416         /* Stop if we're a zombie or need a soft hangup */
1417         ast_pthread_mutex_lock(&chan->lock);
1418         if (!chan->zombie && !ast_check_hangup(chan)) 
1419                 if (chan->pvt->call)
1420                         res = chan->pvt->call(chan, addr, timeout);
1421         pthread_mutex_unlock(&chan->lock);
1422         return res;
1423 }
1424
1425 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1426 {
1427         int pos=0;
1428         int to = ftimeout;
1429         char d;
1430         /* XXX Merge with full version? XXX */
1431         /* Stop if we're a zombie or need a soft hangup */
1432         if (c->zombie || ast_check_hangup(c)) 
1433                 return -1;
1434         if (!len)
1435                 return -1;
1436         do {
1437                 if (c->streamid > -1) {
1438                         d = ast_waitstream(c, AST_DIGIT_ANY);
1439                         ast_stopstream(c);
1440                         usleep(1000);
1441                         if (!d)
1442                                 d = ast_waitfordigit(c, to);
1443                 } else {
1444                         d = ast_waitfordigit(c, to);
1445                 }
1446                 if (d < 0)
1447                         return -1;
1448                 if (d == 0) {
1449                         s[pos]='\0';
1450                         return 1;
1451                 }
1452                 if (!strchr(enders, d))
1453                         s[pos++] = d;
1454                 if (strchr(enders, d) || (pos >= len)) {
1455                         s[pos]='\0';
1456                         return 0;
1457                 }
1458                 to = timeout;
1459         } while(1);
1460         /* Never reached */
1461         return 0;
1462 }
1463
1464 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1465 {
1466         int pos=0;
1467         int to = ftimeout;
1468         char d;
1469         /* Stop if we're a zombie or need a soft hangup */
1470         if (c->zombie || ast_check_hangup(c)) 
1471                 return -1;
1472         if (!len)
1473                 return -1;
1474         do {
1475                 if (c->streamid > -1) {
1476                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1477                         ast_stopstream(c);
1478                         usleep(1000);
1479                         if (!d)
1480                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1481                 } else {
1482                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1483                 }
1484                 if (d < 0)
1485                         return -1;
1486                 if (d == 0) {
1487                         s[pos]='\0';
1488                         return 1;
1489                 }
1490                 if (d == 1) {
1491                         s[pos]='\0';
1492                         return 2;
1493                 }
1494                 if (!strchr(enders, d))
1495                         s[pos++] = d;
1496                 if (strchr(enders, d) || (pos >= len)) {
1497                         s[pos]='\0';
1498                         return 0;
1499                 }
1500                 to = timeout;
1501         } while(1);
1502         /* Never reached */
1503         return 0;
1504 }
1505
1506 int ast_channel_supports_html(struct ast_channel *chan)
1507 {
1508         if (chan->pvt->send_html)
1509                 return 1;
1510         return 0;
1511 }
1512
1513 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1514 {
1515         if (chan->pvt->send_html)
1516                 return chan->pvt->send_html(chan, subclass, data, datalen);
1517         return -1;
1518 }
1519
1520 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1521 {
1522         if (chan->pvt->send_html)
1523                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1524         return -1;
1525 }
1526
1527 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1528 {
1529         int peerf;
1530         int chanf;
1531         int res;
1532         peerf = peer->nativeformats;
1533         chanf = chan->nativeformats;
1534         res = ast_translator_best_choice(&peerf, &chanf);
1535         if (res < 0) {
1536                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1537                 return -1;
1538         }
1539         /* Set read format on channel */
1540         res = ast_set_read_format(chan, peerf);
1541         if (res < 0) {
1542                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1543                 return -1;
1544         }
1545         /* Set write format on peer channel */
1546         res = ast_set_write_format(peer, peerf);
1547         if (res < 0) {
1548                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1549                 return -1;
1550         }
1551         /* Now we go the other way */
1552         peerf = peer->nativeformats;
1553         chanf = chan->nativeformats;
1554         res = ast_translator_best_choice(&chanf, &peerf);
1555         if (res < 0) {
1556                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1557                 return -1;
1558         }
1559         /* Set writeformat on channel */
1560         res = ast_set_write_format(chan, chanf);
1561         if (res < 0) {
1562                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1563                 return -1;
1564         }
1565         /* Set read format on peer channel */
1566         res = ast_set_read_format(peer, chanf);
1567         if (res < 0) {
1568                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1569                 return -1;
1570         }
1571         return 0;
1572 }
1573
1574 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1575 {
1576         struct ast_frame null = { AST_FRAME_NULL, };
1577         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1578                 clone->name, original->name);
1579         if (original->masq) {
1580                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1581                         original->masq->name, original->name);
1582                 return -1;
1583         }
1584         if (clone->masqr) {
1585                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1586                         clone->name, clone->masqr->name);
1587                 return -1;
1588         }
1589         original->masq = clone;
1590         clone->masqr = original;
1591         /* XXX can't really hold the lock here, but at the same time, it' s
1592            not really safe not to XXX */
1593         ast_queue_frame(original, &null, 0);
1594         return 0;
1595 }
1596
1597 void ast_change_name(struct ast_channel *chan, char *newname)
1598 {
1599         char tmp[256];
1600         strncpy(tmp, chan->name, 256);
1601         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1602         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", tmp, chan->name);
1603 }
1604
1605 static int ast_do_masquerade(struct ast_channel *original)
1606 {
1607         int x;
1608         int res=0;
1609         char *tmp;
1610         void *tmpv;
1611         struct ast_channel_pvt *p;
1612         struct ast_channel *clone = original->masq;
1613         int rformat = original->readformat;
1614         int wformat = original->writeformat;
1615         char newn[100];
1616         char orig[100];
1617         char masqn[100];
1618         char zombn[100];
1619         
1620 #if 1
1621         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1622                 clone->name, clone->_state, original->name, original->_state);
1623 #endif
1624         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1625            the clone channel into the original channel.  Start by killing off the original
1626            channel's backend.   I'm not sure we're going to keep this function, because 
1627            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1628
1629         /* Having remembered the original read/write formats, we turn off any translation on either
1630            one */
1631         free_translation(clone);
1632         free_translation(original);
1633
1634         /* We need the clone's lock, too */
1635         ast_pthread_mutex_lock(&clone->lock);
1636
1637         /* Unlink the masquerade */
1638         original->masq = NULL;
1639         clone->masqr = NULL;
1640         
1641         /* Save the original name */
1642         strncpy(orig, original->name, sizeof(orig) - 1);
1643         /* Save the new name */
1644         strncpy(newn, clone->name, sizeof(newn) - 1);
1645         /* Create the masq name */
1646         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1647                 
1648         /* Copy the name from the clone channel */
1649         strncpy(original->name, newn, sizeof(original->name)-1);
1650
1651         /* Mangle the name of the clone channel */
1652         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1653         
1654         /* Notify any managers of the change, first the masq then the other */
1655         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1656         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1657
1658         /* Swap the guts */     
1659         p = original->pvt;
1660         original->pvt = clone->pvt;
1661         clone->pvt = p;
1662         
1663         clone->_softhangup = AST_SOFTHANGUP_DEV;
1664
1665
1666         if (clone->pvt->fixup){
1667                 res = clone->pvt->fixup(original, clone);
1668                 if (res) 
1669                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1670         }
1671
1672         /* Start by disconnecting the original's physical side */
1673         if (clone->pvt->hangup)
1674                 res = clone->pvt->hangup(clone);
1675         if (res) {
1676                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1677                 pthread_mutex_unlock(&clone->lock);
1678                 return -1;
1679         }
1680         
1681         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
1682         /* Mangle the name of the clone channel */
1683         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
1684         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
1685
1686         /* Keep the same language.  */
1687         /* Update the type. */
1688         original->type = clone->type;
1689         /* Copy the FD's */
1690         for (x=0;x<AST_MAX_FDS;x++)
1691                 original->fds[x] = clone->fds[x];
1692         /* Move the variables */
1693         tmpv = original->varshead.first;
1694         original->varshead.first = clone->varshead.first;
1695         clone->varshead.first = tmpv;
1696         /* Presense of ADSI capable CPE follows clone */
1697         original->adsicpe = clone->adsicpe;
1698         /* Bridge remains the same */
1699         /* CDR fields remain the same */
1700         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1701         /* Application and data remain the same */
1702         /* Clone exception  becomes real one, as with fdno */
1703         original->exception = clone->exception;
1704         original->fdno = clone->fdno;
1705         /* Schedule context remains the same */
1706         /* Stream stuff stays the same */
1707         /* Keep the original state.  The fixup code will need to work with it most likely */
1708
1709         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1710            fields back into the defunct 'clone' so that they will be freed when
1711            ast_frfree is eventually called */
1712         tmp = original->dnid;
1713         original->dnid = clone->dnid;
1714         clone->dnid = tmp;
1715         
1716         tmp = original->callerid;
1717         original->callerid = clone->callerid;
1718         clone->callerid = tmp;
1719         
1720         /* Our native formats are different now */
1721         original->nativeformats = clone->nativeformats;
1722
1723         /* And of course, so does our current state.  Note we need not
1724            call ast_setstate since the event manager doesn't really consider
1725            these separate */
1726         original->_state = clone->_state;
1727         
1728         /* Context, extension, priority, app data, jump table,  remain the same */
1729         /* pvt switches.  pbx stays the same, as does next */
1730         
1731         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1732            a zombie so nothing tries to touch it.  If it's already been marked as a
1733            zombie, then free it now (since it already is considered invalid). */
1734         if (clone->zombie) {
1735                 pthread_mutex_unlock(&clone->lock);
1736                 ast_channel_free(clone);
1737                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
1738         } else {
1739                 clone->zombie=1;
1740                 pthread_mutex_unlock(&clone->lock);
1741         }
1742         /* Set the write format */
1743         ast_set_write_format(original, wformat);
1744
1745         /* Set the read format */
1746         ast_set_read_format(original, rformat);
1747
1748         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1749
1750         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1751            can fix up everything as best as possible */
1752         if (original->pvt->fixup) {
1753                 res = original->pvt->fixup(clone, original);
1754                 if (res) {
1755                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1756                                 original->type, original->name);
1757                         return -1;
1758                 }
1759         } else
1760                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1761                         original->type, original->name);
1762         /* Signal any blocker */
1763         if (original->blocking)
1764                 pthread_kill(original->blocker, SIGURG);
1765         return 0;
1766 }
1767
1768 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
1769 {
1770         if (chan->callerid)
1771                 free(chan->callerid);
1772         if (anitoo && chan->ani)
1773                 free(chan->ani);
1774         if (callerid) {
1775                 chan->callerid = strdup(callerid);
1776                 if (anitoo)
1777                         chan->ani = strdup(callerid);
1778         } else {
1779                 chan->callerid = NULL;
1780                 if (anitoo)
1781                         chan->ani = NULL;
1782         }
1783         if (chan->cdr)
1784                 ast_cdr_setcid(chan->cdr, chan);
1785         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
1786                                 "Channel: %s\r\n"
1787                                 "Callerid: %s\r\n",
1788                                 chan->name, chan->callerid ? 
1789                                 chan->callerid : "<Unknown>");
1790 }
1791
1792 int ast_setstate(struct ast_channel *chan, int state)
1793 {
1794         if (chan->_state != state) {
1795                 int oldstate = chan->_state;
1796                 chan->_state = state;
1797                 if (oldstate == AST_STATE_DOWN) {
1798                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1799                         "Channel: %s\r\n"
1800                         "State: %s\r\n"
1801                         "Callerid: %s\r\n",
1802                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1803                 } else {
1804                         manager_event(EVENT_FLAG_CALL, "Newstate", 
1805                                 "Channel: %s\r\n"
1806                                 "State: %s\r\n"
1807                                 "Callerid: %s\r\n",
1808                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1809                 }
1810         }
1811         return 0;
1812 }
1813
1814 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1815 {
1816         /* Copy voice back and forth between the two channels.  Give the peer
1817            the ability to transfer calls with '#<extension' syntax. */
1818         struct ast_channel *cs[3];
1819         int to = -1;
1820         struct ast_frame *f;
1821         struct ast_channel *who = NULL;
1822         int res;
1823         int nativefailed=0;
1824
1825         /* Stop if we're a zombie or need a soft hangup */
1826         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1827                 return -1;
1828         if (c0->bridge) {
1829                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1830                         c0->name, c0->bridge->name);
1831                 return -1;
1832         }
1833         if (c1->bridge) {
1834                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1835                         c1->name, c1->bridge->name);
1836                 return -1;
1837         }
1838         
1839         /* Keep track of bridge */
1840         c0->bridge = c1;
1841         c1->bridge = c0;
1842         cs[0] = c0;
1843         cs[1] = c1;
1844         
1845         manager_event(EVENT_FLAG_CALL, "Link", 
1846                         "Channel1: %s\r\n"
1847                         "Channel2: %s\r\n",
1848                         c0->name, c1->name);
1849
1850         for (/* ever */;;) {
1851                 /* Stop if we're a zombie or need a soft hangup */
1852                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1853                         *fo = NULL;
1854                         if (who) *rc = who;
1855                         res = 0;
1856                         break;
1857                 }
1858                 if (c0->pvt->bridge && 
1859                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1860                                 /* Looks like they share a bridge code */
1861                         if (option_verbose > 2) 
1862                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
1863                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1864                                 c0->bridge = NULL;
1865                                 c1->bridge = NULL;
1866                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1867                                         "Channel1: %s\r\n"
1868                                         "Channel2: %s\r\n",
1869                                         c0->name, c1->name);
1870                                 return 0;
1871                         }
1872                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1873                            my not wanting to bridge */
1874                         if ((res != -2) && (res != -3))
1875                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1876                         if (res != -3) nativefailed++;
1877                 }
1878         
1879                         
1880                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
1881                         !(c0->generator || c1->generator))  {
1882                         if (ast_channel_make_compatible(c0, c1)) {
1883                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1884                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1885                                         "Channel1: %s\r\n"
1886                                         "Channel2: %s\r\n",
1887                                         c0->name, c1->name);
1888                                 return -1;
1889                         }
1890                 }
1891                 who = ast_waitfor_n(cs, 2, &to);
1892                 if (!who) {
1893                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
1894                         continue;
1895                 }
1896                 f = ast_read(who);
1897                 if (!f) {
1898                         *fo = NULL;
1899                         *rc = who;
1900                         res = 0;
1901                         break;
1902                 }
1903
1904                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1905                         *fo = f;
1906                         *rc = who;
1907                         res =  0;
1908                         break;
1909                 }
1910                 if ((f->frametype == AST_FRAME_VOICE) ||
1911                         (f->frametype == AST_FRAME_TEXT) ||
1912                         (f->frametype == AST_FRAME_VIDEO) || 
1913                         (f->frametype == AST_FRAME_IMAGE) ||
1914                         (f->frametype == AST_FRAME_DTMF)) {
1915                         if ((f->frametype == AST_FRAME_DTMF) && 
1916                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1917                                 if ((who == c0)) {
1918                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1919                                                 *rc = c0;
1920                                                 *fo = f;
1921                                                 /* Take out of conference mode */
1922                                                 res = 0;
1923                                                 break;
1924                                         } else 
1925                                                 goto tackygoto;
1926                                 } else
1927                                 if ((who == c1)) {
1928                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1929                                                 *rc = c1;
1930                                                 *fo = f;
1931                                                 res =  0;
1932                                                 break;
1933                                         } else
1934                                                 goto tackygoto;
1935                                 }
1936                         } else {
1937 #if 0
1938                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1939                                 if (who == last) 
1940                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1941                                 last = who;
1942 #endif
1943 tackygoto:
1944                                 /* Don't copy packets if there is a generator on either one, since they're
1945                                    not supposed to be listening anyway */
1946                                 if (who == c0) 
1947                                         ast_write(c1, f);
1948                                 else 
1949                                         ast_write(c0, f);
1950                         }
1951                         ast_frfree(f);
1952                 } else
1953                         ast_frfree(f);
1954                 /* Swap who gets priority */
1955                 cs[2] = cs[0];
1956                 cs[0] = cs[1];
1957                 cs[1] = cs[2];
1958         }
1959         c0->bridge = NULL;
1960         c1->bridge = NULL;
1961         manager_event(EVENT_FLAG_CALL, "Unlink", 
1962                                         "Channel1: %s\r\n"
1963                                         "Channel2: %s\r\n",
1964                                         c0->name, c1->name);
1965         return res;
1966 }
1967
1968 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1969 {
1970         int res;
1971         if (chan->pvt->setoption) {
1972                 res = chan->pvt->setoption(chan, option, data, datalen);
1973                 if (res < 0)
1974                         return res;
1975         } else {
1976                 errno = ENOSYS;
1977                 return -1;
1978         }
1979         if (block) {
1980                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1981                    intermediate packets. XXX */
1982                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1983                 return -1;
1984         }
1985         return 0;
1986 }
1987
1988 struct tonepair_def {
1989         int freq1;
1990         int freq2;
1991         int duration;
1992         int vol;
1993 };
1994
1995 struct tonepair_state {
1996         float freq1;
1997         float freq2;
1998         float vol;
1999         int duration;
2000         int pos;
2001         int origwfmt;
2002         struct ast_frame f;
2003         unsigned char offset[AST_FRIENDLY_OFFSET];
2004         short data[4000];
2005 };
2006
2007 static void tonepair_release(struct ast_channel *chan, void *params)
2008 {
2009         struct tonepair_state *ts = params;
2010         if (chan) {
2011                 ast_set_write_format(chan, ts->origwfmt);
2012         }
2013         free(ts);
2014 }
2015
2016 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2017 {
2018         struct tonepair_state *ts;
2019         struct tonepair_def *td = params;
2020         ts = malloc(sizeof(struct tonepair_state));
2021         if (!ts)
2022                 return NULL;
2023         memset(ts, 0, sizeof(struct tonepair_state));
2024         ts->origwfmt = chan->writeformat;
2025         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2026                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2027                 tonepair_release(NULL, ts);
2028                 ts = NULL;
2029         } else {
2030                 ts->freq1 = td->freq1;
2031                 ts->freq2 = td->freq2;
2032                 ts->duration = td->duration;
2033                 ts->vol = td->vol;
2034         }
2035         /* Let interrupts interrupt :) */
2036         chan->writeinterrupt = 1;
2037         return ts;
2038 }
2039
2040 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2041 {
2042         struct tonepair_state *ts = data;
2043         int x;
2044
2045         /* we need to prepare a frame with 16 * timelen samples as we're 
2046          * generating SLIN audio
2047          */
2048         len = samples * 2;
2049
2050         if (len > sizeof(ts->data) / 2 - 1) {
2051                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2052                 return -1;
2053         }
2054         memset(&ts->f, 0, sizeof(ts->f));
2055         for (x=0;x<len/2;x++) {
2056                 ts->data[x] = ts->vol * (
2057                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2058                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2059                         );
2060         }
2061         ts->f.frametype = AST_FRAME_VOICE;
2062         ts->f.subclass = AST_FORMAT_SLINEAR;
2063         ts->f.datalen = len;
2064         ts->f.samples = samples;
2065         ts->f.offset = AST_FRIENDLY_OFFSET;
2066         ts->f.data = ts->data;
2067         ast_write(chan, &ts->f);
2068         ts->pos += x;
2069         if (ts->duration > 0) {
2070                 if (ts->pos >= ts->duration * 8)
2071                         return -1;
2072         }
2073         return 0;
2074 }
2075
2076 static struct ast_generator tonepair = {
2077         alloc: tonepair_alloc,
2078         release: tonepair_release,
2079         generate: tonepair_generator,
2080 };
2081
2082 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2083 {
2084         struct tonepair_def d = { 0, };
2085         d.freq1 = freq1;
2086         d.freq2 = freq2;
2087         d.duration = duration;
2088         if (vol < 1)
2089                 d.vol = 8192;
2090         else
2091                 d.vol = vol;
2092         if (ast_activate_generator(chan, &tonepair, &d))
2093                 return -1;
2094         return 0;
2095 }
2096
2097 void ast_tonepair_stop(struct ast_channel *chan)
2098 {
2099         ast_deactivate_generator(chan);
2100 }
2101
2102 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2103 {
2104         struct ast_frame *f;
2105         int res;
2106         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2107                 return res;
2108
2109         /* Give us some wiggle room */
2110         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2111                 f = ast_read(chan);
2112                 if (f)
2113                         ast_frfree(f);
2114                 else
2115                         return -1;
2116         }
2117         return 0;
2118 }