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