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