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