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