Version 0.1.12 from FTP
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <pthread.h>
17 #include <string.h>
18 #include <sys/time.h>
19 #include <signal.h>
20 #include <errno.h>
21 #include <asterisk/lock.h>
22 #include <unistd.h>
23 #include <math.h>                       /* For PI */
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
33 static int shutting_down = 0;
34
35 /* XXX Lock appropriately in more functions XXX */
36
37 #ifdef DEBUG_MUTEX
38 /* Convenient mutex debugging functions */
39 #define PTHREAD_MUTEX_LOCK(a) __PTHREAD_MUTEX_LOCK(__FUNCTION__, a)
40 #define PTHREAD_MUTEX_UNLOCK(a) __PTHREAD_MUTEX_UNLOCK(__FUNCTION__, a)
41
42 static int __PTHREAD_MUTEX_LOCK(char *f, pthread_mutex_t *a) {
43         ast_log(LOG_DEBUG, "Locking %p (%s)\n", a, f); 
44         return ast_pthread_mutex_lock(a);
45 }
46
47 static int __PTHREAD_MUTEX_UNLOCK(char *f, pthread_mutex_t *a) {
48         ast_log(LOG_DEBUG, "Unlocking %p (%s)\n", a, f); 
49         return ast_pthread_mutex_unlock(a);
50 }
51 #else
52 #define PTHREAD_MUTEX_LOCK(a) ast_pthread_mutex_lock(a)
53 #define PTHREAD_MUTEX_UNLOCK(a) ast_pthread_mutex_unlock(a)
54 #endif
55
56 struct chanlist {
57         char type[80];
58         char description[80];
59         int capabilities;
60         struct ast_channel * (*requester)(char *type, int format, void *data);
61         struct chanlist *next;
62 } *backends = NULL;
63 struct ast_channel *channels = NULL;
64
65 /* Protect the channel list (highly unlikely that two things would change
66    it at the same time, but still! */
67    
68 static pthread_mutex_t chlock = AST_MUTEX_INITIALIZER;
69
70 int ast_check_hangup(struct ast_channel *chan)
71 {
72 time_t  myt;
73
74           /* if soft hangup flag, return true */
75         if (chan->softhangup) return 1;
76           /* if no hangup scheduled, just return here */
77         if (!chan->whentohangup) return 0;
78         time(&myt); /* get current time */
79           /* return, if not yet */
80         if (chan->whentohangup > myt) return 0;
81         chan->softhangup = 1;
82         return 1;
83 }
84
85 void ast_begin_shutdown(int hangup)
86 {
87         struct ast_channel *c;
88         shutting_down = 1;
89         if (hangup) {
90                 PTHREAD_MUTEX_LOCK(&chlock);
91                 c = channels;
92                 while(c) {
93                         c->softhangup = 1;
94                         c = c->next;
95                 }
96                 PTHREAD_MUTEX_UNLOCK(&chlock);
97         }
98 }
99
100 int ast_active_channels(void)
101 {
102         struct ast_channel *c;
103         int cnt = 0;
104         PTHREAD_MUTEX_LOCK(&chlock);
105         c = channels;
106         while(c) {
107                 cnt++;
108                 c = c->next;
109         }
110         PTHREAD_MUTEX_UNLOCK(&chlock);
111         return cnt;
112 }
113
114 void ast_cancel_shutdown(void)
115 {
116         shutting_down = 0;
117 }
118
119 int ast_shutting_down(void)
120 {
121         return shutting_down;
122 }
123
124 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
125 {
126 time_t  myt;
127
128         time(&myt);
129         chan->whentohangup = myt + offset;
130         return;
131 }
132
133 int ast_channel_register(char *type, char *description, int capabilities,
134                 struct ast_channel *(*requester)(char *type, int format, void *data))
135 {
136         struct chanlist *chan, *last=NULL;
137         if (PTHREAD_MUTEX_LOCK(&chlock)) {
138                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
139                 return -1;
140         }
141         chan = backends;
142         while(chan) {
143                 if (!strcasecmp(type, chan->type)) {
144                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
145                         PTHREAD_MUTEX_UNLOCK(&chlock);
146                         return -1;
147                 }
148                 last = chan;
149                 chan = chan->next;
150         }
151         chan = malloc(sizeof(struct chanlist));
152         if (!chan) {
153                 ast_log(LOG_WARNING, "Out of memory\n");
154                 PTHREAD_MUTEX_UNLOCK(&chlock);
155                 return -1;
156         }
157         strncpy(chan->type, type, sizeof(chan->type)-1);
158         strncpy(chan->description, description, sizeof(chan->description)-1);
159         chan->capabilities = capabilities;
160         chan->requester = requester;
161         chan->next = NULL;
162         if (last)
163                 last->next = chan;
164         else
165                 backends = chan;
166         if (option_debug)
167                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
168         else if (option_verbose > 1)
169                 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
170         PTHREAD_MUTEX_UNLOCK(&chlock);
171         return 0;
172 }
173
174 char *ast_state2str(int state)
175 {
176         switch(state) {
177         case AST_STATE_DOWN:
178                 return "Down";
179         case AST_STATE_RESERVED:
180                 return "Rsrvd";
181         case AST_STATE_OFFHOOK:
182                 return "OffHook";
183         case AST_STATE_DIALING:
184                 return "Dialing";
185         case AST_STATE_RING:
186                 return "Ring";
187         case AST_STATE_RINGING:
188                 return "Ringing";
189         case AST_STATE_UP:
190                 return "Up";
191         case AST_STATE_BUSY:
192                 return "Busy";
193         default:
194                 return "Unknown";
195         }
196 }
197
198
199 int ast_best_codec(int fmts)
200 {
201         /* This just our opinion, expressed in code.  We are asked to choose
202            the best codec to use, given no information */
203         int x;
204         static int prefs[] = 
205         {
206                 /* Okay, ulaw is used by all telephony equipment, so start with it */
207                 AST_FORMAT_ULAW,
208                 /* Unless of course, you're a silly European, so then prefer ALAW */
209                 AST_FORMAT_ALAW,
210                 /* Okay, well, signed linear is easy to translate into other stuff */
211                 AST_FORMAT_SLINEAR,
212                 /* ADPCM has great sound quality and is still pretty easy to translate */
213                 AST_FORMAT_ADPCM,
214                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
215                    translate and sounds pretty good */
216                 AST_FORMAT_GSM,
217                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
218                    to use it */
219                 AST_FORMAT_LPC10,
220                 /* Down to G.723.1 which is proprietary but at least designed for voice */
221                 AST_FORMAT_G723_1,
222                 /* Last and least, MP3 which was of course never designed for real-time voice */
223                 AST_FORMAT_MP3,
224         };
225         
226         
227         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
228                 if (fmts & prefs[x])
229                         return prefs[x];
230         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
231         return 0;
232 }
233
234 struct ast_channel *ast_channel_alloc(int needqueue)
235 {
236         struct ast_channel *tmp;
237         struct ast_channel_pvt *pvt;
238         int x;
239         int flags;
240         /* If shutting down, don't allocate any new channels */
241         if (shutting_down)
242                 return NULL;
243         PTHREAD_MUTEX_LOCK(&chlock);
244         tmp = malloc(sizeof(struct ast_channel));
245         memset(tmp, 0, sizeof(struct ast_channel));
246         if (tmp) {
247                 pvt = malloc(sizeof(struct ast_channel_pvt));
248                 if (pvt) {
249                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
250                         tmp->sched = sched_context_create();
251                         if (tmp->sched) {
252                                 for (x=0;x<AST_MAX_FDS - 1;x++)
253                                         tmp->fds[x] = -1;
254                                 if (needqueue &&  
255                                         pipe(pvt->alertpipe)) {
256                                         ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
257                                         free(pvt);
258                                         free(tmp);
259                                         tmp = NULL;
260                                         pvt = NULL;
261                                 } else {
262                                         /* Make sure we've got it done right if they don't */
263                                         if (needqueue) {
264                                                 flags = fcntl(pvt->alertpipe[0], F_GETFL);
265                                                 fcntl(pvt->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
266                                                 flags = fcntl(pvt->alertpipe[1], F_GETFL);
267                                                 fcntl(pvt->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
268                                         } else
269                                                 pvt->alertpipe[0] = pvt->alertpipe[1] = -1;
270                                         /* Always watch the alertpipe */
271                                         tmp->fds[AST_MAX_FDS-1] = pvt->alertpipe[0];
272                                         strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
273                                         tmp->pvt = pvt;
274                                         tmp->state = AST_STATE_DOWN;
275                                         tmp->stack = -1;
276                                         tmp->streamid = -1;
277                                         tmp->appl = NULL;
278                                         tmp->data = NULL;
279                                         ast_pthread_mutex_init(&tmp->lock);
280                                         strncpy(tmp->context, "default", sizeof(tmp->context)-1);
281                                         strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
282                                         strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
283                                         tmp->priority=1;
284                                         tmp->amaflags = ast_default_amaflags;
285                                         strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
286                                         tmp->next = channels;
287                                         channels= tmp;
288                                 }
289                         } else {
290                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
291                                 free(tmp);
292                                 tmp = NULL;
293                         }
294                 } else {
295                         ast_log(LOG_WARNING, "Out of memory\n");
296                         free(tmp);
297                         tmp = NULL;
298                 }
299         } else 
300                 ast_log(LOG_WARNING, "Out of memory\n");
301         PTHREAD_MUTEX_UNLOCK(&chlock);
302         return tmp;
303 }
304
305 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin, int lock)
306 {
307         struct ast_frame *f;
308         struct ast_frame *prev, *cur;
309         int blah = 1;
310         int qlen = 0;
311         f = ast_frdup(fin);
312         if (!f) {
313                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
314                 return -1;
315         }
316         if (lock)
317                 ast_pthread_mutex_lock(&chan->lock);
318         prev = NULL;
319         cur = chan->pvt->readq;
320         while(cur) {
321                 prev = cur;
322                 cur = cur->next;
323                 qlen++;
324         }
325         if (prev)
326                 prev->next = f;
327         else
328                 chan->pvt->readq = f;
329         if (chan->pvt->alertpipe[1] > -1) {
330                 if (write(chan->pvt->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
331                         ast_log(LOG_WARNING, "Unable to write to alert pipe, frametype/subclass %d/%d (qlen = %d): %s!\n",
332                                 f->frametype, f->subclass, qlen, strerror(errno));
333         }
334         if (qlen  > 128) {
335                 ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
336         }
337         if (lock)
338                 ast_pthread_mutex_unlock(&chan->lock);
339         return 0;
340 }
341
342 int ast_queue_hangup(struct ast_channel *chan, int lock)
343 {
344         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
345         return ast_queue_frame(chan, &f, lock);
346 }
347
348 int ast_queue_control(struct ast_channel *chan, int control, int lock)
349 {
350         struct ast_frame f = { AST_FRAME_CONTROL, };
351         f.subclass = control;
352         return ast_queue_frame(chan, &f, lock);
353 }
354
355 int ast_channel_defer_dtmf(struct ast_channel *chan)
356 {
357         int pre = 0;
358         if (chan) {
359                 pre = chan->deferdtmf;
360                 chan->deferdtmf = 1;
361         }
362         return pre;
363 }
364
365 void ast_channel_undefer_dtmf(struct ast_channel *chan)
366 {
367         if (chan)
368                 chan->deferdtmf = 0;
369 }
370
371 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
372 {
373         struct ast_channel *l, *ret=NULL;
374         PTHREAD_MUTEX_LOCK(&chlock);
375         l = channels;
376         if (!prev) {
377                 PTHREAD_MUTEX_UNLOCK(&chlock);
378                 return l;
379         }
380         while(l) {
381                 if (l == prev)
382                         ret = l->next;
383                 l = l->next;
384         }
385         PTHREAD_MUTEX_UNLOCK(&chlock);
386         return ret;
387         
388 }
389
390 int ast_safe_sleep(struct ast_channel *chan, int ms)
391 {
392         struct ast_frame *f;
393         while(ms > 0) {
394                 ms = ast_waitfor(chan, ms);
395                 if (ms <0)
396                         return -1;
397                 if (ms > 0) {
398                         f = ast_read(chan);
399                         if (!f)
400                                 return -1;
401                         ast_frfree(f);
402                 }
403         }
404         return 0;
405 }
406
407 void ast_channel_free(struct ast_channel *chan)
408 {
409         struct ast_channel *last=NULL, *cur;
410         int fd;
411         struct ast_frame *f, *fp;
412         PTHREAD_MUTEX_LOCK(&chlock);
413         cur = channels;
414         while(cur) {
415                 if (cur == chan) {
416                         if (last)
417                                 last->next = cur->next;
418                         else
419                                 channels = cur->next;
420                         break;
421                 }
422                 last = cur;
423                 cur = cur->next;
424         }
425         if (!cur)
426                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
427         if (chan->pvt->pvt)
428                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
429         /* Free translatosr */
430         if (chan->pvt->readtrans)
431                 ast_translator_free_path(chan->pvt->readtrans);
432         if (chan->pvt->writetrans)
433                 ast_translator_free_path(chan->pvt->writetrans);
434         if (chan->pbx) 
435                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
436         if (chan->dnid)
437                 free(chan->dnid);
438         if (chan->callerid)
439                 free(chan->callerid);   
440         if (chan->ani)
441                 free(chan->ani);
442         pthread_mutex_destroy(&chan->lock);
443         /* Close pipes if appropriate */
444         if ((fd = chan->pvt->alertpipe[0]) > -1)
445                 close(fd);
446         if ((fd = chan->pvt->alertpipe[1]) > -1)
447                 close(fd);
448         f = chan->pvt->readq;
449         while(f) {
450                 fp = f;
451                 f = f->next;
452                 ast_frfree(fp);
453         }
454         free(chan->pvt);
455         free(chan);
456         PTHREAD_MUTEX_UNLOCK(&chlock);
457 }
458
459 int ast_softhangup(struct ast_channel *chan)
460 {
461         int res = 0;
462         if (option_debug)
463                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
464         /* Inform channel driver that we need to be hung up, if it cares */
465         chan->softhangup = 1;           
466         /* Interrupt any select call or such */
467         if (chan->blocking)
468                 pthread_kill(chan->blocker, SIGURG);
469         return res;
470 }
471
472 static void free_translation(struct ast_channel *clone)
473 {
474         if (clone->pvt->writetrans)
475                 ast_translator_free_path(clone->pvt->writetrans);
476         if (clone->pvt->readtrans)
477                 ast_translator_free_path(clone->pvt->readtrans);
478         clone->pvt->writetrans = NULL;
479         clone->pvt->readtrans = NULL;
480         clone->pvt->rawwriteformat = clone->nativeformats;
481         clone->pvt->rawreadformat = clone->nativeformats;
482 }
483
484 int ast_hangup(struct ast_channel *chan)
485 {
486         int res = 0;
487         /* Don't actually hang up a channel that will masquerade as someone else, or
488            if someone is going to masquerade as us */
489         ast_pthread_mutex_lock(&chan->lock);
490         if (chan->masq) {
491                 ast_log(LOG_WARNING, "We're getting hung up, but someone is trying to masq into us?!?\n");
492                 ast_pthread_mutex_unlock(&chan->lock);
493                 return 0;
494         }
495         /* If this channel is one which will be masqueraded into something, 
496            mark it as a zombie already, so we know to free it later */
497         if (chan->masqr) {
498                 ast_pthread_mutex_unlock(&chan->lock);
499                 chan->zombie=1;
500                 return 0;
501         }
502         free_translation(chan);
503         if (chan->stream)
504                 ast_stopstream(chan);
505         if (chan->sched)
506                 sched_context_destroy(chan->sched);
507         /* Clear any tone stuff remaining */
508         if (chan->generatordata)
509                 chan->generator->release(chan, chan->generatordata);
510         chan->generatordata = NULL;
511         chan->generator = NULL;
512         if (chan->cdr) {
513                 /* End the CDR if it hasn't already */
514                 ast_cdr_end(chan->cdr);
515                 /* Post and Free the CDR */
516                 ast_cdr_post(chan->cdr);
517                 ast_cdr_free(chan->cdr);
518         }
519         if (chan->blocking) {
520                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
521                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
522                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
523                 CRASH;
524         }
525         if (!chan->zombie) {
526                 if (option_debug)
527                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
528                 if (chan->pvt->hangup)
529                         res = chan->pvt->hangup(chan);
530         } else
531                 if (option_debug)
532                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
533                         
534         ast_pthread_mutex_unlock(&chan->lock);
535         ast_channel_free(chan);
536         return res;
537 }
538
539 void ast_channel_unregister(char *type)
540 {
541         struct chanlist *chan, *last=NULL;
542         if (option_debug)
543                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
544         if (PTHREAD_MUTEX_LOCK(&chlock)) {
545                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
546                 return;
547         }
548         chan = backends;
549         while(chan) {
550                 if (!strcasecmp(chan->type, type)) {
551                         if (last)
552                                 last->next = chan->next;
553                         else
554                                 backends = backends->next;
555                         free(chan);
556                         PTHREAD_MUTEX_UNLOCK(&chlock);
557                         return;
558                 }
559                 last = chan;
560                 chan = chan->next;
561         }
562         PTHREAD_MUTEX_UNLOCK(&chlock);
563 }
564
565 int ast_answer(struct ast_channel *chan)
566 {
567         int res = 0;
568         /* Stop if we're a zombie or need a soft hangup */
569         if (chan->zombie || ast_check_hangup(chan)) 
570                 return -1;
571         switch(chan->state) {
572         case AST_STATE_RINGING:
573         case AST_STATE_RING:
574                 if (chan->pvt->answer)
575                         res = chan->pvt->answer(chan);
576                 chan->state = AST_STATE_UP;
577                 if (chan->cdr)
578                         ast_cdr_answer(chan->cdr);
579                 return res;
580                 break;
581         case AST_STATE_UP:
582                 break;
583         }
584         return 0;
585 }
586
587 void ast_deactivate_generator(struct ast_channel *chan)
588 {
589         if (chan->generatordata) {
590                 chan->generator->release(chan, chan->generatordata);
591                 chan->generatordata = NULL;
592                 chan->writeinterrupt = 0;
593         }
594 }
595
596 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
597 {
598         if (chan->generatordata) {
599                 chan->generator->release(chan, chan->generatordata);
600                 chan->generatordata = NULL;
601         }
602         if ((chan->generatordata = gen->alloc(chan, params))) {
603                 chan->generator = gen;
604         } else {
605                 return -1;
606         }
607         return 0;
608 }
609
610 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
611 {
612         /* Wait for x amount of time on a file descriptor to have input.  */
613         struct timeval tv;
614         fd_set rfds, efds;
615         int res;
616         int x, max=-1;
617         int winner = -1;
618         
619         tv.tv_sec = *ms / 1000;
620         tv.tv_usec = (*ms % 1000) * 1000;
621         FD_ZERO(&rfds);
622         FD_ZERO(&efds);
623         for (x=0;x<n;x++) {
624                 if (fds[x] > -1) {
625                         FD_SET(fds[x], &rfds);
626                         FD_SET(fds[x], &efds);
627                         if (fds[x] > max)
628                                 max = fds[x];
629                 }
630         }
631         if (*ms >= 0) 
632                 res = select(max + 1, &rfds, NULL, &efds, &tv);
633         else
634                 res = select(max + 1, &rfds, NULL, &efds, NULL);
635
636         if (res < 0) {
637                 /* Simulate a timeout if we were interrupted */
638                 if (errno != EINTR)
639                         *ms = -1;
640                 else
641                         *ms = 0;
642                 return -1;
643         }
644
645         for (x=0;x<n;x++) {
646                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
647                         if (exception)
648                                 *exception = FD_ISSET(fds[x], &efds);
649                         winner = fds[x];
650                 }
651         }
652         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
653         return winner;
654 }
655
656 static int ast_do_masquerade(struct ast_channel *original);
657
658 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
659         int *exception, int *outfd, int *ms)
660 {
661         /* Wait for x amount of time on a file descriptor to have input.  */
662         struct timeval tv;
663         fd_set rfds, efds;
664         int res;
665         int x, y, max=-1;
666         struct ast_channel *winner = NULL;
667         if (outfd)
668                 *outfd = -1;
669         if (exception)
670                 *exception = 0;
671         
672         /* Perform any pending masquerades */
673         for (x=0;x<n;x++) {
674                 if (c[x]->masq) {
675                         if (ast_do_masquerade(c[x])) {
676                                 ast_log(LOG_WARNING, "Masquerade failed\n");
677                                 *ms = -1;
678                                 return NULL;
679                         }
680                 }
681         }
682         
683         tv.tv_sec = *ms / 1000;
684         tv.tv_usec = (*ms % 1000) * 1000;
685         FD_ZERO(&rfds);
686         FD_ZERO(&efds);
687
688         for (x=0;x<n;x++) {
689                 for (y=0;y<AST_MAX_FDS;y++) {
690                         if (c[x]->fds[y] > -1) {
691                                 FD_SET(c[x]->fds[y], &rfds);
692                                 FD_SET(c[x]->fds[y], &efds);
693                                 if (c[x]->fds[y] > max)
694                                         max = c[x]->fds[y];
695                         }
696                 }
697                 CHECK_BLOCKING(c[x]);
698         }
699         for (x=0;x<nfds; x++) {
700                 FD_SET(fds[x], &rfds);
701                 FD_SET(fds[x], &efds);
702                 if (fds[x] > max)
703                         max = fds[x];
704         }
705         if (*ms >= 0) 
706                 res = select(max + 1, &rfds, NULL, &efds, &tv);
707         else
708                 res = select(max + 1, &rfds, NULL, &efds, NULL);
709
710         if (res < 0) {
711                 for (x=0;x<n;x++) 
712                         c[x]->blocking = 0;
713                 /* Simulate a timeout if we were interrupted */
714                 if (errno != EINTR)
715                         *ms = -1;
716                 else {
717                         /* Just an interrupt */
718 #if 0
719                         *ms = 0;
720 #endif                  
721                 }
722                 return NULL;
723         }
724
725         for (x=0;x<n;x++) {
726                 c[x]->blocking = 0;
727                 for (y=0;y<AST_MAX_FDS;y++) {
728                         if (c[x]->fds[y] > -1) {
729                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
730                                         /* Set exception flag if appropriate */
731                                         if (FD_ISSET(c[x]->fds[y], &efds))
732                                                 c[x]->exception = 1;
733                                         c[x]->fdno = y;
734                                         winner = c[x];
735                                 }
736                         }
737                 }
738         }
739         for (x=0;x<nfds;x++) {
740                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
741                         if (outfd)
742                                 *outfd = fds[x];
743                         if (FD_ISSET(fds[x], &efds) && exception)
744                                 *exception = 1;
745                         winner = NULL;
746                 }
747         }
748         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
749         return winner;
750 }
751
752 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
753 {
754         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
755 }
756
757 int ast_waitfor(struct ast_channel *c, int ms)
758 {
759         struct ast_channel *chan;
760         int oldms = ms;
761         chan = ast_waitfor_n(&c, 1, &ms);
762         if (ms < 0) {
763                 if (oldms < 0)
764                         return 0;
765                 else
766                         return -1;
767         }
768         return ms;
769 }
770
771 char ast_waitfordigit(struct ast_channel *c, int ms)
772 {
773         struct ast_frame *f;
774         char result = 0;
775         /* Stop if we're a zombie or need a soft hangup */
776         if (c->zombie || ast_check_hangup(c)) 
777                 return -1;
778         /* Wait for a digit, no more than ms milliseconds total. */
779         while(ms && !result) {
780                 ms = ast_waitfor(c, ms);
781                 if (ms < 0) /* Error */
782                         result = -1; 
783                 else if (ms > 0) {
784                         /* Read something */
785                         f = ast_read(c);
786                         if (f) {
787                                 if (f->frametype == AST_FRAME_DTMF) 
788                                         result = f->subclass;
789                                 ast_frfree(f);
790                         } else
791                                 result = -1;
792                 }
793         }
794         return result;
795 }
796
797 struct ast_frame *ast_read(struct ast_channel *chan)
798 {
799         struct ast_frame *f = NULL;
800         int blah;
801         static struct ast_frame null_frame = 
802         {
803                 AST_FRAME_NULL,
804         };
805         
806         ast_pthread_mutex_lock(&chan->lock);
807         if (chan->masq) {
808                 if (ast_do_masquerade(chan)) {
809                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
810                         f = NULL;
811                 } else
812                         f =  &null_frame;
813                 pthread_mutex_unlock(&chan->lock);
814                 return f;
815         }
816
817         /* Stop if we're a zombie or need a soft hangup */
818         if (chan->zombie || ast_check_hangup(chan)) {
819                 pthread_mutex_unlock(&chan->lock);
820                 return NULL;
821         }
822
823         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
824                 /* We have DTMF that has been deferred.  Return it now */
825                 chan->dtmff.frametype = AST_FRAME_DTMF;
826                 chan->dtmff.subclass = chan->dtmfq[0];
827                 /* Drop first digit */
828                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
829                 pthread_mutex_unlock(&chan->lock);
830                 return &chan->dtmff;
831         }
832         
833         /* Read and ignore anything on the alertpipe, but read only
834            one sizeof(blah) per frame that we send from it */
835         if (chan->pvt->alertpipe[0] > -1) {
836                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
837         }
838
839         /* Check for pending read queue */
840         if (chan->pvt->readq) {
841                 f = chan->pvt->readq;
842                 chan->pvt->readq = f->next;
843                 /* Interpret hangup and return NULL */
844                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
845                         f = NULL;
846         } else {
847                 chan->blocker = pthread_self();
848                 if (chan->exception) {
849                         if (chan->pvt->exception) 
850                                 f = chan->pvt->exception(chan);
851                         else
852                                 ast_log(LOG_WARNING, "Exception flag set, but no exception handler\n");
853                         /* Clear the exception flag */
854                         chan->exception = 0;
855                 } else
856                 if (chan->pvt->read)
857                         f = chan->pvt->read(chan);
858                 else
859                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
860         }
861
862         if (f && (f->frametype == AST_FRAME_VOICE)) {
863                 if (chan->pvt->readtrans) {
864                         f = ast_translate(chan->pvt->readtrans, f, 1);
865                         if (!f)
866                                 f = &null_frame;
867                 }
868         }
869
870         /* Make sure we always return NULL in the future */
871         if (!f) {
872                 chan->softhangup = 1;
873                 /* End the CDR if appropriate */
874                 if (chan->cdr)
875                         ast_cdr_end(chan->cdr);
876         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
877                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
878                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
879                 else
880                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
881                 f = &null_frame;
882         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
883                 /* Answer the CDR */
884                 chan->state = AST_STATE_UP;
885                 ast_cdr_answer(chan->cdr);
886         }
887         pthread_mutex_unlock(&chan->lock);
888
889         /* Run any generator sitting on the line */
890         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
891                 /* Mask generator data temporarily */
892                 void *tmp;
893                 int res;
894                 tmp = chan->generatordata;
895                 chan->generatordata = NULL;
896                 res = chan->generator->generate(chan, tmp, f->datalen);
897                 chan->generatordata = tmp;
898                 if (res) {
899                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
900                         ast_deactivate_generator(chan);
901                 }
902         }
903
904         return f;
905 }
906
907 int ast_indicate(struct ast_channel *chan, int condition)
908 {
909         int res = -1;
910         /* Stop if we're a zombie or need a soft hangup */
911         if (chan->zombie || ast_check_hangup(chan)) 
912                 return -1;
913         if (chan->pvt->indicate) {
914                 res = chan->pvt->indicate(chan, condition);
915                 if (res)
916                         ast_log(LOG_WARNING, "Driver for channel '%s' failed to indicate condition %d\n", chan->name, condition);
917         } else
918                 ast_log(LOG_WARNING, "Driver for channel '%s' does not support indication\n", chan->name);
919         return res;
920 }
921
922 int ast_recvchar(struct ast_channel *chan, int timeout)
923 {
924         int res,ourto,c;
925         struct ast_frame *f;
926         
927         ourto = timeout;
928         for(;;)
929            {
930                 if (ast_check_hangup(chan)) return -1;
931                 res = ast_waitfor(chan,ourto);
932                 if (res <= 0) /* if timeout */
933                    {
934                         return 0;
935                    }
936                 ourto = res;
937                 f = ast_read(chan);
938                 if (f == NULL) return -1; /* if hangup */
939                 if ((f->frametype == AST_FRAME_CONTROL) &&
940                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
941                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
942                    {
943                         c = *((char *)f->data);  /* get the data */
944                         ast_frfree(f);
945                         return(c);
946                    }
947                 ast_frfree(f);
948         }
949 }
950
951 int ast_sendtext(struct ast_channel *chan, char *text)
952 {
953         int res = 0;
954         /* Stop if we're a zombie or need a soft hangup */
955         if (chan->zombie || ast_check_hangup(chan)) 
956                 return -1;
957         CHECK_BLOCKING(chan);
958         if (chan->pvt->send_text)
959                 res = chan->pvt->send_text(chan, text);
960         chan->blocking = 0;
961         return res;
962 }
963
964 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
965 {
966         int res = -1;
967         struct ast_frame *f;
968         /* Stop if we're a zombie or need a soft hangup */
969         if (chan->zombie || ast_check_hangup(chan)) 
970                 return -1;
971         /* Handle any pending masquerades */
972         if (chan->masq) {
973                 if (ast_do_masquerade(chan)) {
974                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
975                         return -1;
976                 }
977         }
978         if (chan->masqr)
979                 return 0;
980         if (chan->generatordata) {
981                 if (chan->writeinterrupt)
982                         ast_deactivate_generator(chan);
983                 else
984                         return 0;
985         }
986         CHECK_BLOCKING(chan);
987         switch(fr->frametype) {
988         case AST_FRAME_CONTROL:
989                 /* XXX Interpret control frames XXX */
990                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
991                 break;
992         case AST_FRAME_DTMF:
993                 if (chan->pvt->send_digit)
994                         res = chan->pvt->send_digit(chan, fr->subclass);
995                 break;
996         case AST_FRAME_TEXT:
997                 if (chan->pvt->send_text)
998                         res = chan->pvt->send_text(chan, (char *) fr->data);
999                 break;
1000         default:
1001                 if (chan->pvt->write) {
1002                         if (chan->pvt->writetrans) {
1003                                 f = ast_translate(chan->pvt->writetrans, fr, 1);
1004                         } else
1005                                 f = fr;
1006                         if (f)  
1007                                 res = chan->pvt->write(chan, f);
1008                         else
1009                                 res = 0;
1010                 }
1011         }
1012         chan->blocking = 0;
1013         /* Consider a write failure to force a soft hangup */
1014         if (res < 0)
1015                 chan->softhangup = 1;
1016         return res;
1017 }
1018
1019 int ast_set_write_format(struct ast_channel *chan, int fmts)
1020 {
1021         int fmt;
1022         int native;
1023         int res;
1024         
1025         native = chan->nativeformats;
1026         fmt = fmts;
1027         
1028         res = ast_translator_best_choice(&native, &fmt);
1029         if (res < 0) {
1030                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1031                 return -1;
1032         }
1033         
1034         /* Now we have a good choice for both.  We'll write using our native format. */
1035         chan->pvt->rawwriteformat = native;
1036         /* User perspective is fmt */
1037         chan->writeformat = fmt;
1038         /* Free any write translation we have right now */
1039         if (chan->pvt->writetrans)
1040                 ast_translator_free_path(chan->pvt->writetrans);
1041         /* Build a translation path from the user write format to the raw writing format */
1042         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1043         if (option_debug)
1044                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1045         return 0;
1046 }
1047
1048 int ast_set_read_format(struct ast_channel *chan, int fmts)
1049 {
1050         int fmt;
1051         int native;
1052         int res;
1053         
1054         native = chan->nativeformats;
1055         fmt = fmts;
1056         /* Find a translation path from the native read format to one of the user's read formats */
1057         res = ast_translator_best_choice(&fmt, &native);
1058         if (res < 0) {
1059                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1060                 return -1;
1061         }
1062         
1063         /* Now we have a good choice for both.  We'll write using our native format. */
1064         chan->pvt->rawreadformat = native;
1065         /* User perspective is fmt */
1066         chan->readformat = fmt;
1067         /* Free any read translation we have right now */
1068         if (chan->pvt->readtrans)
1069                 ast_translator_free_path(chan->pvt->readtrans);
1070         /* Build a translation path from the raw read format to the user reading format */
1071         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1072         if (option_debug)
1073                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1074         return 0;
1075 }
1076
1077 struct ast_channel *ast_request(char *type, int format, void *data)
1078 {
1079         struct chanlist *chan;
1080         struct ast_channel *c = NULL;
1081         int capabilities;
1082         int fmt;
1083         int res;
1084         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1085                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1086                 return NULL;
1087         }
1088         chan = backends;
1089         while(chan) {
1090                 if (!strcasecmp(type, chan->type)) {
1091                         capabilities = chan->capabilities;
1092                         fmt = format;
1093                         res = ast_translator_best_choice(&fmt, &capabilities);
1094                         if (res < 0) {
1095                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1096                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1097                                 return NULL;
1098                         }
1099                         PTHREAD_MUTEX_UNLOCK(&chlock);
1100                         if (chan->requester)
1101                                 c = chan->requester(type, capabilities, data);
1102                         return c;
1103                 }
1104                 chan = chan->next;
1105         }
1106         if (!chan)
1107                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1108         PTHREAD_MUTEX_UNLOCK(&chlock);
1109         return c;
1110 }
1111
1112 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1113 {
1114         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1115            If the remote end does not answer within the timeout, then do NOT hang up, but 
1116            return anyway.  */
1117         int res = -1;
1118         /* Stop if we're a zombie or need a soft hangup */
1119         ast_pthread_mutex_lock(&chan->lock);
1120         if (!chan->zombie && !ast_check_hangup(chan)) 
1121                 if (chan->pvt->call)
1122                         res = chan->pvt->call(chan, addr, timeout);
1123         pthread_mutex_unlock(&chan->lock);
1124         return res;
1125 }
1126
1127 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1128 {
1129         int pos=0;
1130         int to = ftimeout;
1131         char d;
1132         /* Stop if we're a zombie or need a soft hangup */
1133         if (c->zombie || ast_check_hangup(c)) 
1134                 return -1;
1135         if (!len)
1136                 return -1;
1137         do {
1138                 if (c->streamid > -1) {
1139                         d = ast_waitstream(c, AST_DIGIT_ANY);
1140                         ast_stopstream(c);
1141                         usleep(1000);
1142                         if (!d)
1143                                 d = ast_waitfordigit(c, to);
1144                 } else {
1145                         d = ast_waitfordigit(c, to);
1146                 }
1147                 if (d < 0)
1148                         return -1;
1149                 if (d == 0) {
1150                         s[pos]='\0';
1151                         return 1;
1152                 }
1153                 if (!strchr(enders, d))
1154                         s[pos++] = d;
1155                 if (strchr(enders, d) || (pos >= len)) {
1156                         s[pos]='\0';
1157                         return 0;
1158                 }
1159                 to = timeout;
1160         } while(1);
1161         /* Never reached */
1162         return 0;
1163 }
1164
1165 int ast_channel_supports_html(struct ast_channel *chan)
1166 {
1167         if (chan->pvt->send_html)
1168                 return 1;
1169         return 0;
1170 }
1171
1172 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1173 {
1174         if (chan->pvt->send_html)
1175                 return chan->pvt->send_html(chan, subclass, data, datalen);
1176         return -1;
1177 }
1178
1179 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1180 {
1181         if (chan->pvt->send_html)
1182                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1183         return -1;
1184 }
1185
1186 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1187 {
1188         int peerf;
1189         int chanf;
1190         int res;
1191         peerf = peer->nativeformats;
1192         chanf = chan->nativeformats;
1193         res = ast_translator_best_choice(&peerf, &chanf);
1194         if (res < 0) {
1195                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1196                 return -1;
1197         }
1198         /* Set read format on channel */
1199         res = ast_set_read_format(chan, peerf);
1200         if (res < 0) {
1201                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1202                 return -1;
1203         }
1204         /* Set write format on peer channel */
1205         res = ast_set_write_format(peer, peerf);
1206         if (res < 0) {
1207                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1208                 return -1;
1209         }
1210         /* Now we go the other way */
1211         peerf = peer->nativeformats;
1212         chanf = chan->nativeformats;
1213         res = ast_translator_best_choice(&chanf, &peerf);
1214         if (res < 0) {
1215                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1216                 return -1;
1217         }
1218         /* Set writeformat on channel */
1219         res = ast_set_write_format(chan, chanf);
1220         if (res < 0) {
1221                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1222                 return -1;
1223         }
1224         /* Set read format on peer channel */
1225         res = ast_set_read_format(peer, chanf);
1226         if (res < 0) {
1227                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1228                 return -1;
1229         }
1230         return 0;
1231 }
1232
1233 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1234 {
1235         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1236                 clone->name, original->name);
1237         if (original->masq) {
1238                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1239                         original->masq->name, original->name);
1240                 return -1;
1241         }
1242         if (clone->masqr) {
1243                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1244                         clone->name, clone->masqr->name);
1245                 return -1;
1246         }
1247         original->masq = clone;
1248         clone->masqr = original;
1249         return 0;
1250 }
1251
1252 static int ast_do_masquerade(struct ast_channel *original)
1253 {
1254         int x;
1255         int res=0;
1256         char *tmp;
1257         struct ast_channel_pvt *p;
1258         struct ast_channel *clone = original->masq;
1259         int rformat = original->readformat;
1260         int wformat = original->writeformat;
1261         
1262 #if 0
1263         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1264                 clone->name, clone->state, original->name, original->state);
1265 #endif
1266         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1267            the clone channel into the original channel.  Start by killing off the original
1268            channel's backend.   I'm not sure we're going to keep this function, because 
1269            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1270
1271         /* Having remembered the original read/write formats, we turn off any translation on either
1272            one */
1273         free_translation(clone);
1274         free_translation(original);
1275
1276         /* We need the clone's lock, too */
1277         ast_pthread_mutex_lock(&clone->lock);
1278
1279         /* Unlink the masquerade */
1280         original->masq = NULL;
1281         clone->masqr = NULL;
1282                 
1283         /* Copy the name from the clone channel */
1284         strncpy(original->name, clone->name, sizeof(original->name)-1);
1285
1286         /* Mangle the name of the clone channel */
1287         strncat(clone->name, "<MASQ>", sizeof(clone->name));
1288
1289         /* Swap the guts */     
1290         p = original->pvt;
1291         original->pvt = clone->pvt;
1292         clone->pvt = p;
1293         
1294         clone->softhangup = 1;
1295
1296
1297         if (clone->pvt->fixup){
1298                 res = clone->pvt->fixup(original, clone);
1299                 if (res) 
1300                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1301         }
1302
1303         /* Start by disconnecting the original's physical side */
1304         if (clone->pvt->hangup)
1305                 res = clone->pvt->hangup(clone);
1306         if (res) {
1307                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1308                 pthread_mutex_unlock(&clone->lock);
1309                 return -1;
1310         }
1311         
1312         /* Mangle the name of the clone channel */
1313         snprintf(clone->name, sizeof(clone->name), "%s<ZOMBIE>", original->name);
1314
1315         /* Keep the same language.  */
1316         /* Update the type. */
1317         original->type = clone->type;
1318         /* Copy the FD's */
1319         for (x=0;x<AST_MAX_FDS;x++)
1320                 original->fds[x] = clone->fds[x];
1321         /* Presense of ADSI capable CPE follows clone */
1322         original->adsicpe = clone->adsicpe;
1323         /* Bridge remains the same */
1324         /* CDR fields remain the same */
1325         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1326         /* Application and data remain the same */
1327         /* Clone exception  becomes real one, as with fdno */
1328         original->exception = clone->exception;
1329         original->fdno = clone->fdno;
1330         /* Schedule context remains the same */
1331         /* Stream stuff stays the same */
1332         /* Keep the original state.  The fixup code will need to work with it most likely */
1333
1334         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1335            fields back into the defunct 'clone' so that they will be freed when
1336            ast_frfree is eventually called */
1337         tmp = original->dnid;
1338         original->dnid = clone->dnid;
1339         clone->dnid = tmp;
1340         
1341         tmp = original->callerid;
1342         original->callerid = clone->callerid;
1343         clone->callerid = tmp;
1344         
1345         /* Our native formats are different now */
1346         original->nativeformats = clone->nativeformats;
1347         
1348         /* Context, extension, priority, app data, jump table,  remain the same */
1349         /* pvt switches.  pbx stays the same, as does next */
1350         
1351         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1352            a zombie so nothing tries to touch it.  If it's already been marked as a
1353            zombie, then free it now (since it already is considered invalid). */
1354         if (clone->zombie) {
1355                 pthread_mutex_unlock(&clone->lock);
1356                 ast_channel_free(clone);
1357         } else {
1358                 clone->zombie=1;
1359                 pthread_mutex_unlock(&clone->lock);
1360         }
1361         /* Set the write format */
1362         ast_set_write_format(original, wformat);
1363
1364         /* Set the read format */
1365         ast_set_read_format(original, rformat);
1366
1367         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1368
1369         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1370            can fix up everything as best as possible */
1371         if (original->pvt->fixup) {
1372                 res = original->pvt->fixup(clone, original);
1373                 if (res) {
1374                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1375                                 original->type, original->name);
1376                         return -1;
1377                 }
1378         } else
1379                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1380                         original->type, original->name);
1381         /* Signal any blocker */
1382         if (original->blocking)
1383                 pthread_kill(original->blocker, SIGURG);
1384         ast_log(LOG_DEBUG, "Done Masquerading %s(%d) into the structure of %s(%d)\n",
1385                 clone->name, clone->state, original->name, original->state);
1386         return 0;
1387 }
1388
1389 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1390 {
1391         /* Copy voice back and forth between the two channels.  Give the peer
1392            the ability to transfer calls with '#<extension' syntax. */
1393         struct ast_channel *cs[3];
1394         int to = -1;
1395         struct ast_frame *f;
1396         struct ast_channel *who = NULL;
1397         int res;
1398         int nativefailed=0;
1399         /* Stop if we're a zombie or need a soft hangup */
1400         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1401                 return -1;
1402         if (c0->bridge) {
1403                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1404                         c0->name, c0->bridge->name);
1405                 return -1;
1406         }
1407         if (c1->bridge) {
1408                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1409                         c1->name, c1->bridge->name);
1410                 return -1;
1411         }
1412         
1413         /* Keep track of bridge */
1414         c0->bridge = c1;
1415         c1->bridge = c0;
1416         cs[0] = c0;
1417         cs[1] = c1;
1418         for (/* ever */;;) {
1419                 /* Stop if we're a zombie or need a soft hangup */
1420                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1421                         *fo = NULL;
1422                         if (who) *rc = who;
1423                         res = 0;
1424                         break;
1425                 }
1426                 if (c0->pvt->bridge && 
1427                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1428                                 /* Looks like they share a bridge code */
1429                         if (option_verbose > 2) 
1430                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
1431                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1432                                 c0->bridge = NULL;
1433                                 c1->bridge = NULL;
1434                                 return 0;
1435                         }
1436                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1437                            my not wanting to bridge */
1438                         if ((res != -2) && (res != -3))
1439                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1440                         if (res != -3) nativefailed++;
1441                 }
1442         
1443                         
1444                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
1445                         !(c0->generator || c1->generator))  {
1446                         if (ast_channel_make_compatible(c0, c1)) {
1447                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1448                                 return -1;
1449                         }
1450                 }
1451                 who = ast_waitfor_n(cs, 2, &to);
1452                 if (!who) {
1453                         ast_log(LOG_WARNING, "Nobody there??\n"); 
1454                         continue;
1455                 }
1456                 f = ast_read(who);
1457                 if (!f) {
1458                         *fo = NULL;
1459                         *rc = who;
1460                         res = 0;
1461                         break;
1462                 }
1463                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1464                         *fo = f;
1465                         *rc = who;
1466                         res =  0;
1467                         break;
1468                 }
1469                 if ((f->frametype == AST_FRAME_VOICE) ||
1470                         (f->frametype == AST_FRAME_TEXT) ||
1471                         (f->frametype == AST_FRAME_VIDEO) || 
1472                         (f->frametype == AST_FRAME_IMAGE) ||
1473                         (f->frametype == AST_FRAME_DTMF)) {
1474                         if ((f->frametype == AST_FRAME_DTMF) && 
1475                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1476                                 if ((who == c0)) {
1477                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1478                                                 *rc = c0;
1479                                                 *fo = f;
1480                                                 /* Take out of conference mode */
1481                                                 res = 0;
1482                                                 break;
1483                                         } else 
1484                                                 goto tackygoto;
1485                                 } else
1486                                 if ((who == c1)) {
1487                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1488                                                 *rc = c1;
1489                                                 *fo = f;
1490                                                 res =  0;
1491                                                 break;
1492                                         } else
1493                                                 goto tackygoto;
1494                                 }
1495                         } else {
1496 #if 0
1497                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1498                                 if (who == last) 
1499                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1500                                 last = who;
1501 #endif
1502 tackygoto:
1503                                 /* Don't copy packets if there is a generator on either one, since they're
1504                                    not supposed to be listening anyway */
1505                                 if (!c0->generator && !c1->generator) {
1506                                         if (who == c0) 
1507                                                 ast_write(c1, f);
1508                                         else 
1509                                                 ast_write(c0, f);
1510                                 }
1511                         }
1512                         ast_frfree(f);
1513                 } else
1514                         ast_frfree(f);
1515                 /* Swap who gets priority */
1516                 cs[2] = cs[0];
1517                 cs[0] = cs[1];
1518                 cs[1] = cs[2];
1519         }
1520         c0->bridge = NULL;
1521         c1->bridge = NULL;
1522         return res;
1523 }
1524
1525 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1526 {
1527         int res;
1528         if (chan->pvt->setoption) {
1529                 res = chan->pvt->setoption(chan, option, data, datalen);
1530                 if (res < 0)
1531                         return res;
1532         } else {
1533                 errno = ENOSYS;
1534                 return -1;
1535         }
1536         if (block) {
1537                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1538                    intermediate packets. XXX */
1539                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1540                 return -1;
1541         }
1542         return 0;
1543 }
1544
1545 struct tonepair_def {
1546         int freq1;
1547         int freq2;
1548         int duration;
1549         int vol;
1550 };
1551
1552 struct tonepair_state {
1553         float freq1;
1554         float freq2;
1555         float vol;
1556         int duration;
1557         int pos;
1558         int origrfmt;
1559         int origwfmt;
1560         struct ast_frame f;
1561         unsigned char offset[AST_FRIENDLY_OFFSET];
1562         short data[4000];
1563 };
1564
1565 static void tonepair_release(struct ast_channel *chan, void *params)
1566 {
1567         struct tonepair_state *ts = params;
1568         if (chan) {
1569                 ast_set_write_format(chan, ts->origwfmt);
1570                 ast_set_read_format(chan, ts->origrfmt);
1571         }
1572         free(ts);
1573 }
1574
1575 static void * tonepair_alloc(struct ast_channel *chan, void *params)
1576 {
1577         struct tonepair_state *ts;
1578         struct tonepair_def *td = params;
1579         ts = malloc(sizeof(struct tonepair_state));
1580         if (!ts)
1581                 return NULL;
1582         memset(ts, 0, sizeof(struct tonepair_state));
1583         ts->origrfmt = chan->readformat;
1584         ts->origwfmt = chan->writeformat;
1585         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
1586                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
1587                 tonepair_release(NULL, ts);
1588                 ts = NULL;
1589         } else if (ast_set_read_format(chan, AST_FORMAT_SLINEAR)) {
1590                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (read)\n", chan->name);
1591                 ast_set_write_format(chan, ts->origwfmt);
1592                 tonepair_release(NULL, ts);
1593                 ts = NULL;
1594         } else {
1595                 ts->freq1 = td->freq1;
1596                 ts->freq2 = td->freq2;
1597                 ts->duration = td->duration;
1598                 ts->vol = td->vol;
1599         }
1600         /* Let interrupts interrupt :) */
1601         chan->writeinterrupt = 1;
1602         return ts;
1603 }
1604
1605 static int tonepair_generator(struct ast_channel *chan, void *data, int len)
1606 {
1607         struct tonepair_state *ts = data;
1608         int x;
1609         if (len > sizeof(ts->data) / 2 - 1) {
1610                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
1611                 return -1;
1612         }
1613         memset(&ts->f, 0, sizeof(ts->f));
1614         for (x=0;x<len/2;x++) {
1615                 ts->data[x] = ts->vol * (
1616                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
1617                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
1618                         );
1619         }
1620         ts->f.frametype = AST_FRAME_VOICE;
1621         ts->f.subclass = AST_FORMAT_SLINEAR;
1622         ts->f.datalen = len;
1623         ts->f.timelen = len/8;
1624         ts->f.offset = AST_FRIENDLY_OFFSET;
1625         ts->f.data = ts->data;
1626         ast_write(chan, &ts->f);
1627         ts->pos += x;
1628         if (ts->duration > 0) {
1629                 if (ts->pos >= ts->duration * 8)
1630                         return -1;
1631         }
1632         return 0;
1633 }
1634
1635 static struct ast_generator tonepair = {
1636         alloc: tonepair_alloc,
1637         release: tonepair_release,
1638         generate: tonepair_generator,
1639 };
1640
1641 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
1642 {
1643         struct tonepair_def d = { 0, };
1644         d.freq1 = freq1;
1645         d.freq2 = freq2;
1646         d.duration = duration;
1647         if (vol < 1)
1648                 d.vol = 8192;
1649         else
1650                 d.vol = vol;
1651         if (ast_activate_generator(chan, &tonepair, &d))
1652                 return -1;
1653         return 0;
1654 }
1655
1656 void ast_tonepair_stop(struct ast_channel *chan)
1657 {
1658         ast_deactivate_generator(chan);
1659 }
1660
1661 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
1662 {
1663         struct ast_frame *f;
1664         int res;
1665         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
1666                 return res;
1667
1668         /* Give us some wiggle room */
1669         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
1670                 f = ast_read(chan);
1671                 if (f)
1672                         ast_frfree(f);
1673                 else
1674                         return -1;
1675         }
1676         return 0;
1677 }