dom mar 16 23:37:23 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         /* XXX Should I be merged with waitfordigit_full XXX */
873         struct ast_frame *f;
874         char result = 0;
875         /* Stop if we're a zombie or need a soft hangup */
876         if (c->zombie || ast_check_hangup(c)) 
877                 return -1;
878         /* Wait for a digit, no more than ms milliseconds total. */
879         while(ms && !result) {
880                 ms = ast_waitfor(c, ms);
881                 if (ms < 0) /* Error */
882                         result = -1; 
883                 else if (ms > 0) {
884                         /* Read something */
885                         f = ast_read(c);
886                         if (f) {
887                                 if (f->frametype == AST_FRAME_DTMF) 
888                                         result = f->subclass;
889                                 ast_frfree(f);
890                         } else
891                                 result = -1;
892                 }
893         }
894         return result;
895 }
896
897 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
898 {
899         struct ast_frame *f;
900         char result = 0;
901         struct ast_channel *rchan;
902         int outfd;
903         /* Stop if we're a zombie or need a soft hangup */
904         if (c->zombie || ast_check_hangup(c)) 
905                 return -1;
906         /* Wait for a digit, no more than ms milliseconds total. */
907         while(ms && !result) {
908                 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
909                 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
910                         result = -1; 
911                 else if (outfd > -1) {
912                         result = 1;
913                 } else if (rchan) {
914                         /* Read something */
915                         f = ast_read(c);
916                         if (f) {
917                                 if (f->frametype == AST_FRAME_DTMF) 
918                                         result = f->subclass;
919                                 ast_frfree(f);
920                         } else
921                                 result = -1;
922                 }
923         }
924         return result;
925 }
926
927 struct ast_frame *ast_read(struct ast_channel *chan)
928 {
929         struct ast_frame *f = NULL;
930         int blah;
931         static struct ast_frame null_frame = 
932         {
933                 AST_FRAME_NULL,
934         };
935         
936         ast_pthread_mutex_lock(&chan->lock);
937         if (chan->masq) {
938                 if (ast_do_masquerade(chan)) {
939                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
940                         f = NULL;
941                 } else
942                         f =  &null_frame;
943                 pthread_mutex_unlock(&chan->lock);
944                 return f;
945         }
946
947         /* Stop if we're a zombie or need a soft hangup */
948         if (chan->zombie || ast_check_hangup(chan)) {
949                 if (chan->generator)
950                         ast_deactivate_generator(chan);
951                 pthread_mutex_unlock(&chan->lock);
952                 return NULL;
953         }
954
955         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
956                 /* We have DTMF that has been deferred.  Return it now */
957                 chan->dtmff.frametype = AST_FRAME_DTMF;
958                 chan->dtmff.subclass = chan->dtmfq[0];
959                 /* Drop first digit */
960                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
961                 pthread_mutex_unlock(&chan->lock);
962                 return &chan->dtmff;
963         }
964         
965         /* Read and ignore anything on the alertpipe, but read only
966            one sizeof(blah) per frame that we send from it */
967         if (chan->pvt->alertpipe[0] > -1) {
968                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
969         }
970
971         /* Check for pending read queue */
972         if (chan->pvt->readq) {
973                 f = chan->pvt->readq;
974                 chan->pvt->readq = f->next;
975                 /* Interpret hangup and return NULL */
976                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
977                         f = NULL;
978         } else {
979                 chan->blocker = pthread_self();
980                 if (chan->exception) {
981                         if (chan->pvt->exception) 
982                                 f = chan->pvt->exception(chan);
983                         else {
984                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
985                                 f = &null_frame;
986                         }
987                         /* Clear the exception flag */
988                         chan->exception = 0;
989                 } else
990                 if (chan->pvt->read)
991                         f = chan->pvt->read(chan);
992                 else
993                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
994         }
995
996
997         if (f && (f->frametype == AST_FRAME_VOICE)) {
998                 if (!(f->subclass & chan->nativeformats)) {
999                         /* This frame can't be from the current native formats -- drop it on the
1000                            floor */
1001                         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);
1002                         ast_frfree(f);
1003                         f = &null_frame;
1004                 } else if (chan->pvt->readtrans) {
1005                         f = ast_translate(chan->pvt->readtrans, f, 1);
1006                         if (!f)
1007                                 f = &null_frame;
1008                 }
1009         }
1010
1011         /* Make sure we always return NULL in the future */
1012         if (!f) {
1013                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1014                 if (chan->generator)
1015                         ast_deactivate_generator(chan);
1016                 /* End the CDR if appropriate */
1017                 if (chan->cdr)
1018                         ast_cdr_end(chan->cdr);
1019         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1020                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1021                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1022                 else
1023                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1024                 f = &null_frame;
1025         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1026                 /* Answer the CDR */
1027                 ast_setstate(chan, AST_STATE_UP);
1028                 ast_cdr_answer(chan->cdr);
1029         }
1030         pthread_mutex_unlock(&chan->lock);
1031
1032         /* Run any generator sitting on the line */
1033         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1034                 /* Mask generator data temporarily */
1035                 void *tmp;
1036                 int res;
1037                 tmp = chan->generatordata;
1038                 chan->generatordata = NULL;
1039                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1040                 chan->generatordata = tmp;
1041                 if (res) {
1042                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1043                         ast_deactivate_generator(chan);
1044                 }
1045         }
1046         if (chan->fin & 0x80000000)
1047                 ast_frame_dump(chan->name, f, "<<");
1048         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1049                 chan->fin &= 0x80000000;
1050         else
1051                 chan->fin++;
1052         return f;
1053 }
1054
1055 int ast_indicate(struct ast_channel *chan, int condition)
1056 {
1057         int res = -1;
1058         /* Stop if we're a zombie or need a soft hangup */
1059         if (chan->zombie || ast_check_hangup(chan)) 
1060                 return -1;
1061         if (chan->pvt->indicate)
1062                 res = chan->pvt->indicate(chan, condition);
1063         if (!chan->pvt->indicate || res) {
1064                 /*
1065                  * Device does not support (that) indication, lets fake
1066                  * it by doing our own tone generation. (PM2002)
1067                  */
1068                 if (condition >= 0) {
1069                         const struct tone_zone_sound *ts = NULL;
1070                         switch (condition) {
1071                          case AST_CONTROL_RINGING:
1072                                 ts = ast_get_indication_tone(chan->zone, "ring");
1073                                 break;
1074                          case AST_CONTROL_BUSY:
1075                                 ts = ast_get_indication_tone(chan->zone, "busy");
1076                                 break;
1077                          case AST_CONTROL_CONGESTION:
1078                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1079                                 break;
1080                         }
1081                         if (ts && ts->data[0]) {
1082                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1083                                 ast_playtones_start(chan,0,ts->data, 1);
1084                         }
1085                         else  {
1086                                 /* not handled */
1087                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1088                                 return -1;
1089                         }
1090                 }
1091                 else ast_playtones_stop(chan);
1092         }
1093         return 0;
1094 }
1095
1096 int ast_recvchar(struct ast_channel *chan, int timeout)
1097 {
1098         int res,ourto,c;
1099         struct ast_frame *f;
1100         
1101         ourto = timeout;
1102         for(;;)
1103            {
1104                 if (ast_check_hangup(chan)) return -1;
1105                 res = ast_waitfor(chan,ourto);
1106                 if (res <= 0) /* if timeout */
1107                    {
1108                         return 0;
1109                    }
1110                 ourto = res;
1111                 f = ast_read(chan);
1112                 if (f == NULL) return -1; /* if hangup */
1113                 if ((f->frametype == AST_FRAME_CONTROL) &&
1114                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1115                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1116                    {
1117                         c = *((char *)f->data);  /* get the data */
1118                         ast_frfree(f);
1119                         return(c);
1120                    }
1121                 ast_frfree(f);
1122         }
1123 }
1124
1125 int ast_sendtext(struct ast_channel *chan, char *text)
1126 {
1127         int res = 0;
1128         /* Stop if we're a zombie or need a soft hangup */
1129         if (chan->zombie || ast_check_hangup(chan)) 
1130                 return -1;
1131         CHECK_BLOCKING(chan);
1132         if (chan->pvt->send_text)
1133                 res = chan->pvt->send_text(chan, text);
1134         chan->blocking = 0;
1135         return res;
1136 }
1137
1138 static int do_senddigit(struct ast_channel *chan, char digit)
1139 {
1140         int res = -1;
1141
1142         if (chan->pvt->send_digit)
1143                 res = chan->pvt->send_digit(chan, digit);
1144         if (!chan->pvt->send_digit || res) {
1145                 /*
1146                  * Device does not support DTMF tones, lets fake
1147                  * it by doing our own generation. (PM2002)
1148                  */
1149                 static const char* dtmf_tones[] = {
1150                         "!941+1336/50,!0/50",   /* 0 */
1151                         "!697+1209/50,!0/50",   /* 1 */
1152                         "!697+1336/50,!0/50",   /* 2 */
1153                         "!697+1477/50,!0/50",   /* 3 */
1154                         "!770+1209/50,!0/50",   /* 4 */
1155                         "!770+1336/50,!0/50",   /* 5 */
1156                         "!770+1477/50,!0/50",   /* 6 */
1157                         "!852+1209/50,!0/50",   /* 7 */
1158                         "!852+1336/50,!0/50",   /* 8 */
1159                         "!852+1477/50,!0/50",   /* 9 */
1160                         "!697+1633/50,!0/50",   /* A */
1161                         "!770+1633/50,!0/50",   /* B */
1162                         "!852+1633/50,!0/50",   /* C */
1163                         "!941+1633/50,!0/50",   /* D */
1164                         "!941+1209/50,!0/50",   /* * */
1165                         "!941+1477/50,!0/50" }; /* # */
1166                 if (digit >= '0' && digit <='9')
1167                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1168                 else if (digit >= 'A' && digit <= 'D')
1169                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1170                 else if (digit == '*')
1171                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1172                 else if (digit == '#')
1173                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1174                 else {
1175                         /* not handled */
1176                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1177                         return -1;
1178                 }
1179         }
1180         return 0;
1181 }
1182
1183 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1184 {
1185         int res = -1;
1186         struct ast_frame *f = NULL;
1187         /* Stop if we're a zombie or need a soft hangup */
1188         if (chan->zombie || ast_check_hangup(chan)) 
1189                 return -1;
1190         /* Handle any pending masquerades */
1191         if (chan->masq) {
1192                 if (ast_do_masquerade(chan)) {
1193                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1194                         return -1;
1195                 }
1196         }
1197         if (chan->masqr)
1198                 return 0;
1199         if (chan->generatordata) {
1200                 if (chan->writeinterrupt)
1201                         ast_deactivate_generator(chan);
1202                 else
1203                         return 0;
1204         }
1205         if (chan->fout & 0x80000000)
1206                 ast_frame_dump(chan->name, fr, ">>");
1207         CHECK_BLOCKING(chan);
1208         switch(fr->frametype) {
1209         case AST_FRAME_CONTROL:
1210                 /* XXX Interpret control frames XXX */
1211                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1212                 break;
1213         case AST_FRAME_DTMF:
1214                 res = do_senddigit(chan,fr->subclass);
1215                 break;
1216         case AST_FRAME_TEXT:
1217                 if (chan->pvt->send_text)
1218                         res = chan->pvt->send_text(chan, (char *) fr->data);
1219                 break;
1220         default:
1221                 if (chan->pvt->write) {
1222                         if (chan->pvt->writetrans) {
1223                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1224                         } else
1225                                 f = fr;
1226                         if (f)  
1227                                 res = chan->pvt->write(chan, f);
1228                         else
1229                                 res = 0;
1230                 }
1231         }
1232         if (f && (f != fr))
1233                 ast_frfree(f);
1234         chan->blocking = 0;
1235         /* Consider a write failure to force a soft hangup */
1236         if (res < 0)
1237                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1238         else {
1239                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1240                         chan->fout &= 0x80000000;
1241                 else
1242                         chan->fout++;
1243                 chan->fout++;
1244         }
1245         return res;
1246 }
1247
1248 int ast_set_write_format(struct ast_channel *chan, int fmts)
1249 {
1250         int fmt;
1251         int native;
1252         int res;
1253         
1254         native = chan->nativeformats;
1255         fmt = fmts;
1256         
1257         res = ast_translator_best_choice(&native, &fmt);
1258         if (res < 0) {
1259                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1260                 return -1;
1261         }
1262         
1263         /* Now we have a good choice for both.  We'll write using our native format. */
1264         chan->pvt->rawwriteformat = native;
1265         /* User perspective is fmt */
1266         chan->writeformat = fmt;
1267         /* Free any write translation we have right now */
1268         if (chan->pvt->writetrans)
1269                 ast_translator_free_path(chan->pvt->writetrans);
1270         /* Build a translation path from the user write format to the raw writing format */
1271         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1272         if (option_debug)
1273                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1274         return 0;
1275 }
1276
1277 int ast_set_read_format(struct ast_channel *chan, int fmts)
1278 {
1279         int fmt;
1280         int native;
1281         int res;
1282         
1283         native = chan->nativeformats;
1284         fmt = fmts;
1285         /* Find a translation path from the native read format to one of the user's read formats */
1286         res = ast_translator_best_choice(&fmt, &native);
1287         if (res < 0) {
1288                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1289                 return -1;
1290         }
1291         
1292         /* Now we have a good choice for both.  We'll write using our native format. */
1293         chan->pvt->rawreadformat = native;
1294         /* User perspective is fmt */
1295         chan->readformat = fmt;
1296         /* Free any read translation we have right now */
1297         if (chan->pvt->readtrans)
1298                 ast_translator_free_path(chan->pvt->readtrans);
1299         /* Build a translation path from the raw read format to the user reading format */
1300         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1301         if (option_debug)
1302                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1303         return 0;
1304 }
1305
1306 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1307 {
1308         int state = 0;
1309         struct ast_channel *chan;
1310         struct ast_frame *f;
1311         int res;
1312         
1313         chan = ast_request(type, format, data);
1314         if (chan) {
1315                 if (callerid)
1316                         ast_set_callerid(chan, callerid, 1);
1317                 if (!ast_call(chan, data, 0)) {
1318                         while(timeout && (chan->_state != AST_STATE_UP)) {
1319                                 res = ast_waitfor(chan, timeout);
1320                                 if (res < 0) {
1321                                         /* Something not cool, or timed out */
1322                                         ast_hangup(chan);
1323                                         chan = NULL;
1324                                         break;
1325                                 }
1326                                 /* If done, break out */
1327                                 if (!res)
1328                                         break;
1329                                 if (timeout > -1)
1330                                         timeout = res;
1331                                 f = ast_read(chan);
1332                                 if (!f) {
1333                                         state = AST_CONTROL_HANGUP;
1334                                         ast_hangup(chan);
1335                                         chan = NULL;
1336                                         break;
1337                                 }
1338                                 if (f->frametype == AST_FRAME_CONTROL) {
1339                                         if (f->subclass == AST_CONTROL_RINGING)
1340                                                 state = AST_CONTROL_RINGING;
1341                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1342                                                 state = f->subclass;
1343                                                 break;
1344                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1345                                                 state = f->subclass;
1346                                                 break;
1347                                         } else {
1348                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1349                                         }
1350                                 }
1351                                 ast_frfree(f);
1352                         }
1353                 } else {
1354                         ast_hangup(chan);
1355                         chan = NULL;
1356                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1357                 }
1358         } else
1359                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1360         if (chan && (chan->_state == AST_STATE_UP))
1361                 state = AST_CONTROL_ANSWER;
1362         if (outstate)
1363                 *outstate = state;
1364         return chan;
1365 }
1366
1367 struct ast_channel *ast_request(char *type, int format, void *data)
1368 {
1369         struct chanlist *chan;
1370         struct ast_channel *c = NULL;
1371         int capabilities;
1372         int fmt;
1373         int res;
1374         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1375                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1376                 return NULL;
1377         }
1378         chan = backends;
1379         while(chan) {
1380                 if (!strcasecmp(type, chan->type)) {
1381                         capabilities = chan->capabilities;
1382                         fmt = format;
1383                         res = ast_translator_best_choice(&fmt, &capabilities);
1384                         if (res < 0) {
1385                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1386                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1387                                 return NULL;
1388                         }
1389                         PTHREAD_MUTEX_UNLOCK(&chlock);
1390                         if (chan->requester)
1391                                 c = chan->requester(type, capabilities, data);
1392                         if (c) {
1393                                 manager_event(EVENT_FLAG_CALL, "Newchannel",
1394                                 "Channel: %s\r\n"
1395                                 "State: %s\r\n"
1396                                 "Callerid: %s\r\n",
1397                                 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>");
1398                         }
1399                         return c;
1400                 }
1401                 chan = chan->next;
1402         }
1403         if (!chan)
1404                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1405         PTHREAD_MUTEX_UNLOCK(&chlock);
1406         return c;
1407 }
1408
1409 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1410 {
1411         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1412            If the remote end does not answer within the timeout, then do NOT hang up, but 
1413            return anyway.  */
1414         int res = -1;
1415         /* Stop if we're a zombie or need a soft hangup */
1416         ast_pthread_mutex_lock(&chan->lock);
1417         if (!chan->zombie && !ast_check_hangup(chan)) 
1418                 if (chan->pvt->call)
1419                         res = chan->pvt->call(chan, addr, timeout);
1420         pthread_mutex_unlock(&chan->lock);
1421         return res;
1422 }
1423
1424 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1425 {
1426         int pos=0;
1427         int to = ftimeout;
1428         char d;
1429         /* XXX Merge with full version? XXX */
1430         /* Stop if we're a zombie or need a soft hangup */
1431         if (c->zombie || ast_check_hangup(c)) 
1432                 return -1;
1433         if (!len)
1434                 return -1;
1435         do {
1436                 if (c->streamid > -1) {
1437                         d = ast_waitstream(c, AST_DIGIT_ANY);
1438                         ast_stopstream(c);
1439                         usleep(1000);
1440                         if (!d)
1441                                 d = ast_waitfordigit(c, to);
1442                 } else {
1443                         d = ast_waitfordigit(c, to);
1444                 }
1445                 if (d < 0)
1446                         return -1;
1447                 if (d == 0) {
1448                         s[pos]='\0';
1449                         return 1;
1450                 }
1451                 if (!strchr(enders, d))
1452                         s[pos++] = d;
1453                 if (strchr(enders, d) || (pos >= len)) {
1454                         s[pos]='\0';
1455                         return 0;
1456                 }
1457                 to = timeout;
1458         } while(1);
1459         /* Never reached */
1460         return 0;
1461 }
1462
1463 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1464 {
1465         int pos=0;
1466         int to = ftimeout;
1467         char d;
1468         /* Stop if we're a zombie or need a soft hangup */
1469         if (c->zombie || ast_check_hangup(c)) 
1470                 return -1;
1471         if (!len)
1472                 return -1;
1473         do {
1474                 if (c->streamid > -1) {
1475                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1476                         ast_stopstream(c);
1477                         usleep(1000);
1478                         if (!d)
1479                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1480                 } else {
1481                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1482                 }
1483                 if (d < 0)
1484                         return -1;
1485                 if (d == 0) {
1486                         s[pos]='\0';
1487                         return 1;
1488                 }
1489                 if (d == 1) {
1490                         s[pos]='\0';
1491                         return 2;
1492                 }
1493                 if (!strchr(enders, d))
1494                         s[pos++] = d;
1495                 if (strchr(enders, d) || (pos >= len)) {
1496                         s[pos]='\0';
1497                         return 0;
1498                 }
1499                 to = timeout;
1500         } while(1);
1501         /* Never reached */
1502         return 0;
1503 }
1504
1505 int ast_channel_supports_html(struct ast_channel *chan)
1506 {
1507         if (chan->pvt->send_html)
1508                 return 1;
1509         return 0;
1510 }
1511
1512 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1513 {
1514         if (chan->pvt->send_html)
1515                 return chan->pvt->send_html(chan, subclass, data, datalen);
1516         return -1;
1517 }
1518
1519 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1520 {
1521         if (chan->pvt->send_html)
1522                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1523         return -1;
1524 }
1525
1526 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1527 {
1528         int peerf;
1529         int chanf;
1530         int res;
1531         peerf = peer->nativeformats;
1532         chanf = chan->nativeformats;
1533         res = ast_translator_best_choice(&peerf, &chanf);
1534         if (res < 0) {
1535                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1536                 return -1;
1537         }
1538         /* Set read format on channel */
1539         res = ast_set_read_format(chan, peerf);
1540         if (res < 0) {
1541                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1542                 return -1;
1543         }
1544         /* Set write format on peer channel */
1545         res = ast_set_write_format(peer, peerf);
1546         if (res < 0) {
1547                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1548                 return -1;
1549         }
1550         /* Now we go the other way */
1551         peerf = peer->nativeformats;
1552         chanf = chan->nativeformats;
1553         res = ast_translator_best_choice(&chanf, &peerf);
1554         if (res < 0) {
1555                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1556                 return -1;
1557         }
1558         /* Set writeformat on channel */
1559         res = ast_set_write_format(chan, chanf);
1560         if (res < 0) {
1561                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1562                 return -1;
1563         }
1564         /* Set read format on peer channel */
1565         res = ast_set_read_format(peer, chanf);
1566         if (res < 0) {
1567                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1568                 return -1;
1569         }
1570         return 0;
1571 }
1572
1573 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1574 {
1575         struct ast_frame null = { AST_FRAME_NULL, };
1576         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1577                 clone->name, original->name);
1578         if (original->masq) {
1579                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1580                         original->masq->name, original->name);
1581                 return -1;
1582         }
1583         if (clone->masqr) {
1584                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1585                         clone->name, clone->masqr->name);
1586                 return -1;
1587         }
1588         original->masq = clone;
1589         clone->masqr = original;
1590         /* XXX can't really hold the lock here, but at the same time, it' s
1591            not really safe not to XXX */
1592         ast_queue_frame(original, &null, 0);
1593         return 0;
1594 }
1595
1596 void ast_change_name(struct ast_channel *chan, char *newname)
1597 {
1598         char tmp[256];
1599         strncpy(tmp, chan->name, 256);
1600         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1601         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", tmp, chan->name);
1602 }
1603
1604 static int ast_do_masquerade(struct ast_channel *original)
1605 {
1606         int x;
1607         int res=0;
1608         char *tmp;
1609         void *tmpv;
1610         struct ast_channel_pvt *p;
1611         struct ast_channel *clone = original->masq;
1612         int rformat = original->readformat;
1613         int wformat = original->writeformat;
1614         char newn[100];
1615         char orig[100];
1616         char masqn[100];
1617         char zombn[100];
1618         
1619 #if 1
1620         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1621                 clone->name, clone->_state, original->name, original->_state);
1622 #endif
1623         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1624            the clone channel into the original channel.  Start by killing off the original
1625            channel's backend.   I'm not sure we're going to keep this function, because 
1626            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1627
1628         /* Having remembered the original read/write formats, we turn off any translation on either
1629            one */
1630         free_translation(clone);
1631         free_translation(original);
1632
1633         /* We need the clone's lock, too */
1634         ast_pthread_mutex_lock(&clone->lock);
1635
1636         /* Unlink the masquerade */
1637         original->masq = NULL;
1638         clone->masqr = NULL;
1639         
1640         /* Save the original name */
1641         strncpy(orig, original->name, sizeof(orig) - 1);
1642         /* Save the new name */
1643         strncpy(newn, clone->name, sizeof(newn) - 1);
1644         /* Create the masq name */
1645         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1646                 
1647         /* Copy the name from the clone channel */
1648         strncpy(original->name, newn, sizeof(original->name)-1);
1649
1650         /* Mangle the name of the clone channel */
1651         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1652         
1653         /* Notify any managers of the change, first the masq then the other */
1654         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1655         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1656
1657         /* Swap the guts */     
1658         p = original->pvt;
1659         original->pvt = clone->pvt;
1660         clone->pvt = p;
1661         
1662         clone->_softhangup = AST_SOFTHANGUP_DEV;
1663
1664
1665         if (clone->pvt->fixup){
1666                 res = clone->pvt->fixup(original, clone);
1667                 if (res) 
1668                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1669         }
1670
1671         /* Start by disconnecting the original's physical side */
1672         if (clone->pvt->hangup)
1673                 res = clone->pvt->hangup(clone);
1674         if (res) {
1675                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1676                 pthread_mutex_unlock(&clone->lock);
1677                 return -1;
1678         }
1679         
1680         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
1681         /* Mangle the name of the clone channel */
1682         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
1683         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
1684
1685         /* Keep the same language.  */
1686         /* Update the type. */
1687         original->type = clone->type;
1688         /* Copy the FD's */
1689         for (x=0;x<AST_MAX_FDS;x++)
1690                 original->fds[x] = clone->fds[x];
1691         /* Move the variables */
1692         tmpv = original->varshead.first;
1693         original->varshead.first = clone->varshead.first;
1694         clone->varshead.first = tmpv;
1695         /* Presense of ADSI capable CPE follows clone */
1696         original->adsicpe = clone->adsicpe;
1697         /* Bridge remains the same */
1698         /* CDR fields remain the same */
1699         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1700         /* Application and data remain the same */
1701         /* Clone exception  becomes real one, as with fdno */
1702         original->exception = clone->exception;
1703         original->fdno = clone->fdno;
1704         /* Schedule context remains the same */
1705         /* Stream stuff stays the same */
1706         /* Keep the original state.  The fixup code will need to work with it most likely */
1707
1708         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1709            fields back into the defunct 'clone' so that they will be freed when
1710            ast_frfree is eventually called */
1711         tmp = original->dnid;
1712         original->dnid = clone->dnid;
1713         clone->dnid = tmp;
1714         
1715         tmp = original->callerid;
1716         original->callerid = clone->callerid;
1717         clone->callerid = tmp;
1718         
1719         /* Our native formats are different now */
1720         original->nativeformats = clone->nativeformats;
1721
1722         /* And of course, so does our current state.  Note we need not
1723            call ast_setstate since the event manager doesn't really consider
1724            these separate */
1725         original->_state = clone->_state;
1726         
1727         /* Context, extension, priority, app data, jump table,  remain the same */
1728         /* pvt switches.  pbx stays the same, as does next */
1729         
1730         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1731            a zombie so nothing tries to touch it.  If it's already been marked as a
1732            zombie, then free it now (since it already is considered invalid). */
1733         if (clone->zombie) {
1734                 pthread_mutex_unlock(&clone->lock);
1735                 ast_channel_free(clone);
1736                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
1737         } else {
1738                 clone->zombie=1;
1739                 pthread_mutex_unlock(&clone->lock);
1740         }
1741         /* Set the write format */
1742         ast_set_write_format(original, wformat);
1743
1744         /* Set the read format */
1745         ast_set_read_format(original, rformat);
1746
1747         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1748
1749         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1750            can fix up everything as best as possible */
1751         if (original->pvt->fixup) {
1752                 res = original->pvt->fixup(clone, original);
1753                 if (res) {
1754                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1755                                 original->type, original->name);
1756                         return -1;
1757                 }
1758         } else
1759                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1760                         original->type, original->name);
1761         /* Signal any blocker */
1762         if (original->blocking)
1763                 pthread_kill(original->blocker, SIGURG);
1764         return 0;
1765 }
1766
1767 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
1768 {
1769         if (chan->callerid)
1770                 free(chan->callerid);
1771         if (anitoo && chan->ani)
1772                 free(chan->ani);
1773         if (callerid) {
1774                 chan->callerid = strdup(callerid);
1775                 if (anitoo)
1776                         chan->ani = strdup(callerid);
1777         } else {
1778                 chan->callerid = NULL;
1779                 if (anitoo)
1780                         chan->ani = NULL;
1781         }
1782         if (chan->cdr)
1783                 ast_cdr_setcid(chan->cdr, chan);
1784         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
1785                                 "Channel: %s\r\n"
1786                                 "Callerid: %s\r\n",
1787                                 chan->name, chan->callerid ? 
1788                                 chan->callerid : "<Unknown>");
1789 }
1790
1791 int ast_setstate(struct ast_channel *chan, int state)
1792 {
1793         if (chan->_state != state) {
1794                 int oldstate = chan->_state;
1795                 chan->_state = state;
1796                 if (oldstate == AST_STATE_DOWN) {
1797                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1798                         "Channel: %s\r\n"
1799                         "State: %s\r\n"
1800                         "Callerid: %s\r\n",
1801                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1802                 } else {
1803                         manager_event(EVENT_FLAG_CALL, "Newstate", 
1804                                 "Channel: %s\r\n"
1805                                 "State: %s\r\n"
1806                                 "Callerid: %s\r\n",
1807                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1808                 }
1809         }
1810         return 0;
1811 }
1812
1813 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1814 {
1815         /* Copy voice back and forth between the two channels.  Give the peer
1816            the ability to transfer calls with '#<extension' syntax. */
1817         struct ast_channel *cs[3];
1818         int to = -1;
1819         struct ast_frame *f;
1820         struct ast_channel *who = NULL;
1821         int res;
1822         int nativefailed=0;
1823
1824         /* Stop if we're a zombie or need a soft hangup */
1825         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1826                 return -1;
1827         if (c0->bridge) {
1828                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1829                         c0->name, c0->bridge->name);
1830                 return -1;
1831         }
1832         if (c1->bridge) {
1833                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1834                         c1->name, c1->bridge->name);
1835                 return -1;
1836         }
1837         
1838         /* Keep track of bridge */
1839         c0->bridge = c1;
1840         c1->bridge = c0;
1841         cs[0] = c0;
1842         cs[1] = c1;
1843         
1844         manager_event(EVENT_FLAG_CALL, "Link", 
1845                         "Channel1: %s\r\n"
1846                         "Channel2: %s\r\n",
1847                         c0->name, c1->name);
1848
1849         for (/* ever */;;) {
1850                 /* Stop if we're a zombie or need a soft hangup */
1851                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1852                         *fo = NULL;
1853                         if (who) *rc = who;
1854                         res = 0;
1855                         break;
1856                 }
1857                 if (c0->pvt->bridge && 
1858                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1859                                 /* Looks like they share a bridge code */
1860                         if (option_verbose > 2) 
1861                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
1862                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1863                                 c0->bridge = NULL;
1864                                 c1->bridge = NULL;
1865                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1866                                         "Channel1: %s\r\n"
1867                                         "Channel2: %s\r\n",
1868                                         c0->name, c1->name);
1869                                 return 0;
1870                         }
1871                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1872                            my not wanting to bridge */
1873                         if ((res != -2) && (res != -3))
1874                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1875                         if (res != -3) nativefailed++;
1876                 }
1877         
1878                         
1879                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
1880                         !(c0->generator || c1->generator))  {
1881                         if (ast_channel_make_compatible(c0, c1)) {
1882                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1883                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
1884                                         "Channel1: %s\r\n"
1885                                         "Channel2: %s\r\n",
1886                                         c0->name, c1->name);
1887                                 return -1;
1888                         }
1889                 }
1890                 who = ast_waitfor_n(cs, 2, &to);
1891                 if (!who) {
1892                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
1893                         continue;
1894                 }
1895                 f = ast_read(who);
1896                 if (!f) {
1897                         *fo = NULL;
1898                         *rc = who;
1899                         res = 0;
1900                         break;
1901                 }
1902
1903                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1904                         *fo = f;
1905                         *rc = who;
1906                         res =  0;
1907                         break;
1908                 }
1909                 if ((f->frametype == AST_FRAME_VOICE) ||
1910                         (f->frametype == AST_FRAME_TEXT) ||
1911                         (f->frametype == AST_FRAME_VIDEO) || 
1912                         (f->frametype == AST_FRAME_IMAGE) ||
1913                         (f->frametype == AST_FRAME_DTMF)) {
1914                         if ((f->frametype == AST_FRAME_DTMF) && 
1915                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1916                                 if ((who == c0)) {
1917                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1918                                                 *rc = c0;
1919                                                 *fo = f;
1920                                                 /* Take out of conference mode */
1921                                                 res = 0;
1922                                                 break;
1923                                         } else 
1924                                                 goto tackygoto;
1925                                 } else
1926                                 if ((who == c1)) {
1927                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1928                                                 *rc = c1;
1929                                                 *fo = f;
1930                                                 res =  0;
1931                                                 break;
1932                                         } else
1933                                                 goto tackygoto;
1934                                 }
1935                         } else {
1936 #if 0
1937                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1938                                 if (who == last) 
1939                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1940                                 last = who;
1941 #endif
1942 tackygoto:
1943                                 /* Don't copy packets if there is a generator on either one, since they're
1944                                    not supposed to be listening anyway */
1945                                 if (who == c0) 
1946                                         ast_write(c1, f);
1947                                 else 
1948                                         ast_write(c0, f);
1949                         }
1950                         ast_frfree(f);
1951                 } else
1952                         ast_frfree(f);
1953                 /* Swap who gets priority */
1954                 cs[2] = cs[0];
1955                 cs[0] = cs[1];
1956                 cs[1] = cs[2];
1957         }
1958         c0->bridge = NULL;
1959         c1->bridge = NULL;
1960         manager_event(EVENT_FLAG_CALL, "Unlink", 
1961                                         "Channel1: %s\r\n"
1962                                         "Channel2: %s\r\n",
1963                                         c0->name, c1->name);
1964         return res;
1965 }
1966
1967 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1968 {
1969         int res;
1970         if (chan->pvt->setoption) {
1971                 res = chan->pvt->setoption(chan, option, data, datalen);
1972                 if (res < 0)
1973                         return res;
1974         } else {
1975                 errno = ENOSYS;
1976                 return -1;
1977         }
1978         if (block) {
1979                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1980                    intermediate packets. XXX */
1981                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1982                 return -1;
1983         }
1984         return 0;
1985 }
1986
1987 struct tonepair_def {
1988         int freq1;
1989         int freq2;
1990         int duration;
1991         int vol;
1992 };
1993
1994 struct tonepair_state {
1995         float freq1;
1996         float freq2;
1997         float vol;
1998         int duration;
1999         int pos;
2000         int origwfmt;
2001         struct ast_frame f;
2002         unsigned char offset[AST_FRIENDLY_OFFSET];
2003         short data[4000];
2004 };
2005
2006 static void tonepair_release(struct ast_channel *chan, void *params)
2007 {
2008         struct tonepair_state *ts = params;
2009         if (chan) {
2010                 ast_set_write_format(chan, ts->origwfmt);
2011         }
2012         free(ts);
2013 }
2014
2015 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2016 {
2017         struct tonepair_state *ts;
2018         struct tonepair_def *td = params;
2019         ts = malloc(sizeof(struct tonepair_state));
2020         if (!ts)
2021                 return NULL;
2022         memset(ts, 0, sizeof(struct tonepair_state));
2023         ts->origwfmt = chan->writeformat;
2024         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2025                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2026                 tonepair_release(NULL, ts);
2027                 ts = NULL;
2028         } else {
2029                 ts->freq1 = td->freq1;
2030                 ts->freq2 = td->freq2;
2031                 ts->duration = td->duration;
2032                 ts->vol = td->vol;
2033         }
2034         /* Let interrupts interrupt :) */
2035         chan->writeinterrupt = 1;
2036         return ts;
2037 }
2038
2039 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2040 {
2041         struct tonepair_state *ts = data;
2042         int x;
2043
2044         /* we need to prepare a frame with 16 * timelen samples as we're 
2045          * generating SLIN audio
2046          */
2047         len = samples * 2;
2048
2049         if (len > sizeof(ts->data) / 2 - 1) {
2050                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2051                 return -1;
2052         }
2053         memset(&ts->f, 0, sizeof(ts->f));
2054         for (x=0;x<len/2;x++) {
2055                 ts->data[x] = ts->vol * (
2056                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2057                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2058                         );
2059         }
2060         ts->f.frametype = AST_FRAME_VOICE;
2061         ts->f.subclass = AST_FORMAT_SLINEAR;
2062         ts->f.datalen = len;
2063         ts->f.samples = samples;
2064         ts->f.offset = AST_FRIENDLY_OFFSET;
2065         ts->f.data = ts->data;
2066         ast_write(chan, &ts->f);
2067         ts->pos += x;
2068         if (ts->duration > 0) {
2069                 if (ts->pos >= ts->duration * 8)
2070                         return -1;
2071         }
2072         return 0;
2073 }
2074
2075 static struct ast_generator tonepair = {
2076         alloc: tonepair_alloc,
2077         release: tonepair_release,
2078         generate: tonepair_generator,
2079 };
2080
2081 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2082 {
2083         struct tonepair_def d = { 0, };
2084         d.freq1 = freq1;
2085         d.freq2 = freq2;
2086         d.duration = duration;
2087         if (vol < 1)
2088                 d.vol = 8192;
2089         else
2090                 d.vol = vol;
2091         if (ast_activate_generator(chan, &tonepair, &d))
2092                 return -1;
2093         return 0;
2094 }
2095
2096 void ast_tonepair_stop(struct ast_channel *chan)
2097 {
2098         ast_deactivate_generator(chan);
2099 }
2100
2101 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2102 {
2103         struct ast_frame *f;
2104         int res;
2105         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2106                 return res;
2107
2108         /* Give us some wiggle room */
2109         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2110                 f = ast_read(chan);
2111                 if (f)
2112                         ast_frfree(f);
2113                 else
2114                         return -1;
2115         }
2116         return 0;
2117 }