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