Version 0.1.11 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 <unistd.h>
22 #include <asterisk/frame.h>
23 #include <asterisk/sched.h>
24 #include <asterisk/options.h>
25 #include <asterisk/channel.h>
26 #include <asterisk/channel_pvt.h>
27 #include <asterisk/logger.h>
28 #include <asterisk/file.h>
29 #include <asterisk/translate.h>
30
31
32 /* XXX Lock appropriately in more functions XXX */
33
34 #ifdef DEBUG_MUTEX
35 /* Convenient mutex debugging functions */
36 #define PTHREAD_MUTEX_LOCK(a) __PTHREAD_MUTEX_LOCK(__FUNCTION__, a)
37 #define PTHREAD_MUTEX_UNLOCK(a) __PTHREAD_MUTEX_UNLOCK(__FUNCTION__, a)
38
39 static int __PTHREAD_MUTEX_LOCK(char *f, pthread_mutex_t *a) {
40         ast_log(LOG_DEBUG, "Locking %p (%s)\n", a, f); 
41         return ast_pthread_mutex_lock(a);
42 }
43
44 static int __PTHREAD_MUTEX_UNLOCK(char *f, pthread_mutex_t *a) {
45         ast_log(LOG_DEBUG, "Unlocking %p (%s)\n", a, f); 
46         return ast_pthread_mutex_unlock(a);
47 }
48 #else
49 #define PTHREAD_MUTEX_LOCK(a) ast_pthread_mutex_lock(a)
50 #define PTHREAD_MUTEX_UNLOCK(a) ast_pthread_mutex_unlock(a)
51 #endif
52
53 struct chanlist {
54         char type[80];
55         char description[80];
56         int capabilities;
57         struct ast_channel * (*requester)(char *type, int format, void *data);
58         struct chanlist *next;
59 } *backends = NULL;
60 struct ast_channel *channels = NULL;
61
62 /* Protect the channel list (highly unlikely that two things would change
63    it at the same time, but still! */
64    
65 static pthread_mutex_t chlock = PTHREAD_MUTEX_INITIALIZER;
66
67 int ast_check_hangup(struct ast_channel *chan)
68 {
69 time_t  myt;
70
71           /* if soft hangup flag, return true */
72         if (chan->softhangup) return 1;
73           /* if no hangup scheduled, just return here */
74         if (!chan->whentohangup) return 0;
75         time(&myt); /* get current time */
76           /* return, if not yet */
77         if (chan->whentohangup > myt) return 0;
78         chan->softhangup = 1;
79         return 1;
80 }
81
82 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
83 {
84 time_t  myt;
85
86         time(&myt);
87         chan->whentohangup = myt + offset;
88         return;
89 }
90
91 int ast_channel_register(char *type, char *description, int capabilities,
92                 struct ast_channel *(*requester)(char *type, int format, void *data))
93 {
94         struct chanlist *chan, *last=NULL;
95         if (PTHREAD_MUTEX_LOCK(&chlock)) {
96                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
97                 return -1;
98         }
99         chan = backends;
100         while(chan) {
101                 if (!strcasecmp(type, chan->type)) {
102                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", type);
103                         PTHREAD_MUTEX_UNLOCK(&chlock);
104                         return -1;
105                 }
106                 last = chan;
107                 chan = chan->next;
108         }
109         chan = malloc(sizeof(struct chanlist));
110         if (!chan) {
111                 ast_log(LOG_WARNING, "Out of memory\n");
112                 PTHREAD_MUTEX_UNLOCK(&chlock);
113                 return -1;
114         }
115         strncpy(chan->type, type, sizeof(chan->type)-1);
116         strncpy(chan->description, description, sizeof(chan->description)-1);
117         chan->capabilities = capabilities;
118         chan->requester = requester;
119         chan->next = NULL;
120         if (last)
121                 last->next = chan;
122         else
123                 backends = chan;
124         if (option_debug)
125                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->type, chan->description);
126         else if (option_verbose > 1)
127                 ast_verbose( VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->type, chan->description);
128         PTHREAD_MUTEX_UNLOCK(&chlock);
129         return 0;
130 }
131
132 char *ast_state2str(int state)
133 {
134         switch(state) {
135         case AST_STATE_DOWN:
136                 return "Down";
137         case AST_STATE_RESERVED:
138                 return "Rsrvd";
139         case AST_STATE_OFFHOOK:
140                 return "OffHook";
141         case AST_STATE_DIALING:
142                 return "Dialing";
143         case AST_STATE_RING:
144                 return "Ring";
145         case AST_STATE_RINGING:
146                 return "Ringing";
147         case AST_STATE_UP:
148                 return "Up";
149         case AST_STATE_BUSY:
150                 return "Busy";
151         default:
152                 return "Unknown";
153         }
154 }
155
156
157 int ast_best_codec(int fmts)
158 {
159         /* This just our opinion, expressed in code.  We are asked to choose
160            the best codec to use, given no information */
161         int x;
162         static int prefs[] = 
163         {
164                 /* Okay, ulaw is used by all telephony equipment, so start with it */
165                 AST_FORMAT_ULAW,
166                 /* Unless of course, you're a silly European, so then prefer ALAW */
167                 AST_FORMAT_ALAW,
168                 /* Okay, well, signed linear is easy to translate into other stuff */
169                 AST_FORMAT_SLINEAR,
170                 /* ADPCM has great sound quality and is still pretty easy to translate */
171                 AST_FORMAT_ADPCM,
172                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
173                    translate and sounds pretty good */
174                 AST_FORMAT_GSM,
175                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
176                    to use it */
177                 AST_FORMAT_LPC10,
178                 /* Down to G.723.1 which is proprietary but at least designed for voice */
179                 AST_FORMAT_G723_1,
180                 /* Last and least, MP3 which was of course never designed for real-time voice */
181                 AST_FORMAT_MP3,
182         };
183         
184         
185         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
186                 if (fmts & prefs[x])
187                         return prefs[x];
188         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
189         return 0;
190 }
191
192 struct ast_channel *ast_channel_alloc(void)
193 {
194         struct ast_channel *tmp;
195         struct ast_channel_pvt *pvt;
196         int x;
197         PTHREAD_MUTEX_LOCK(&chlock);
198         tmp = malloc(sizeof(struct ast_channel));
199         memset(tmp, 0, sizeof(struct ast_channel));
200         if (tmp) {
201                 pvt = malloc(sizeof(struct ast_channel_pvt));
202                 if (pvt) {
203                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
204                         tmp->sched = sched_context_create();
205                         if (tmp->sched) {
206                                 for (x=0;x<AST_MAX_FDS;x++)
207                                         tmp->fds[x] = -1;
208                                 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
209                                 tmp->pvt = pvt;
210                                 tmp->state = AST_STATE_DOWN;
211                                 tmp->stack = -1;
212                                 tmp->streamid = -1;
213                                 tmp->appl = NULL;
214                                 tmp->data = NULL;
215                                 pthread_mutex_init(&tmp->lock, NULL);
216                                 strncpy(tmp->context, "default", sizeof(tmp->context)-1);
217                                 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
218                                 strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
219                                 tmp->priority=1;
220                                 tmp->amaflags = ast_default_amaflags;
221                                 strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
222                                 tmp->next = channels;
223                                 channels= tmp;
224                         } else {
225                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
226                                 free(tmp);
227                                 tmp = NULL;
228                         }
229                 } else {
230                         ast_log(LOG_WARNING, "Out of memory\n");
231                         free(tmp);
232                         tmp = NULL;
233                 }
234         } else 
235                 ast_log(LOG_WARNING, "Out of memory\n");
236         PTHREAD_MUTEX_UNLOCK(&chlock);
237         return tmp;
238 }
239
240 int ast_channel_defer_dtmf(struct ast_channel *chan)
241 {
242         int pre = 0;
243         if (chan) {
244                 pre = chan->deferdtmf;
245                 chan->deferdtmf = 1;
246         }
247         return pre;
248 }
249
250 void ast_channel_undefer_dtmf(struct ast_channel *chan)
251 {
252         if (chan)
253                 chan->deferdtmf = 0;
254 }
255
256 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
257 {
258         struct ast_channel *l, *ret=NULL;
259         PTHREAD_MUTEX_LOCK(&chlock);
260         l = channels;
261         if (!prev) {
262                 PTHREAD_MUTEX_UNLOCK(&chlock);
263                 return l;
264         }
265         while(l) {
266                 if (l == prev)
267                         ret = l->next;
268                 l = l->next;
269         }
270         PTHREAD_MUTEX_UNLOCK(&chlock);
271         return ret;
272         
273 }
274
275 void ast_channel_free(struct ast_channel *chan)
276 {
277         struct ast_channel *last=NULL, *cur;
278         PTHREAD_MUTEX_LOCK(&chlock);
279         cur = channels;
280         while(cur) {
281                 if (cur == chan) {
282                         if (last)
283                                 last->next = cur->next;
284                         else
285                                 channels = cur->next;
286                         break;
287                 }
288                 last = cur;
289                 cur = cur->next;
290         }
291         if (!cur)
292                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
293         if (chan->pvt->pvt)
294                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
295         /* Free translatosr */
296         if (chan->pvt->readtrans)
297                 ast_translator_free_path(chan->pvt->readtrans);
298         if (chan->pvt->writetrans)
299                 ast_translator_free_path(chan->pvt->writetrans);
300         if (chan->pbx) 
301                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
302         if (chan->dnid)
303                 free(chan->dnid);
304         if (chan->callerid)
305                 free(chan->callerid);   
306         if (chan->ani)
307                 free(chan->ani);
308         pthread_mutex_destroy(&chan->lock);
309         free(chan->pvt);
310         free(chan);
311         PTHREAD_MUTEX_UNLOCK(&chlock);
312 }
313
314 int ast_softhangup(struct ast_channel *chan)
315 {
316         int res = 0;
317         if (option_debug)
318                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
319         /* Inform channel driver that we need to be hung up, if it cares */
320         chan->softhangup = 1;           
321         /* Interrupt any select call or such */
322         if (chan->blocking)
323                 pthread_kill(chan->blocker, SIGURG);
324         return res;
325 }
326
327 static void free_translation(struct ast_channel *clone)
328 {
329         if (clone->pvt->writetrans)
330                 ast_translator_free_path(clone->pvt->writetrans);
331         if (clone->pvt->readtrans)
332                 ast_translator_free_path(clone->pvt->readtrans);
333         clone->pvt->writetrans = NULL;
334         clone->pvt->readtrans = NULL;
335         clone->pvt->rawwriteformat = clone->nativeformats;
336         clone->pvt->rawreadformat = clone->nativeformats;
337 }
338
339 int ast_hangup(struct ast_channel *chan)
340 {
341         int res = 0;
342         /* Don't actually hang up a channel that will masquerade as someone else, or
343            if someone is going to masquerade as us */
344         ast_pthread_mutex_lock(&chan->lock);
345         if (chan->masq) {
346                 ast_log(LOG_WARNING, "We're getting hung up, but someone is trying to masq into us?!?\n");
347                 ast_pthread_mutex_unlock(&chan->lock);
348                 return 0;
349         }
350         /* If this channel is one which will be masqueraded into something, 
351            mark it as a zombie already, so we know to free it later */
352         if (chan->masqr) {
353                 ast_pthread_mutex_unlock(&chan->lock);
354                 chan->zombie=1;
355                 return 0;
356         }
357         free_translation(chan);
358         if (chan->stream)
359                 ast_stopstream(chan);
360         if (chan->sched)
361                 sched_context_destroy(chan->sched);
362         if (chan->cdr) {
363                 /* End the CDR if it hasn't already */
364                 ast_cdr_end(chan->cdr);
365                 /* Post and Free the CDR */
366                 ast_cdr_post(chan->cdr);
367                 ast_cdr_free(chan->cdr);
368         }
369         if (chan->blocking) {
370                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
371                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
372                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
373                 CRASH;
374         }
375         if (!chan->zombie) {
376                 if (option_debug)
377                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
378                 if (chan->pvt->hangup)
379                         res = chan->pvt->hangup(chan);
380         } else
381                 if (option_debug)
382                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
383                         
384         ast_pthread_mutex_unlock(&chan->lock);
385         ast_channel_free(chan);
386         return res;
387 }
388
389 void ast_channel_unregister(char *type)
390 {
391         struct chanlist *chan, *last=NULL;
392         if (option_debug)
393                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
394         if (PTHREAD_MUTEX_LOCK(&chlock)) {
395                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
396                 return;
397         }
398         chan = backends;
399         while(chan) {
400                 if (!strcasecmp(chan->type, type)) {
401                         if (last)
402                                 last->next = chan->next;
403                         else
404                                 backends = backends->next;
405                         free(chan);
406                         PTHREAD_MUTEX_UNLOCK(&chlock);
407                         return;
408                 }
409                 last = chan;
410                 chan = chan->next;
411         }
412         PTHREAD_MUTEX_UNLOCK(&chlock);
413 }
414
415 int ast_answer(struct ast_channel *chan)
416 {
417         int res = 0;
418         /* Stop if we're a zombie or need a soft hangup */
419         if (chan->zombie || ast_check_hangup(chan)) 
420                 return -1;
421         switch(chan->state) {
422         case AST_STATE_RINGING:
423         case AST_STATE_RING:
424                 if (chan->pvt->answer)
425                         res = chan->pvt->answer(chan);
426                 chan->state = AST_STATE_UP;
427                 if (chan->cdr)
428                         ast_cdr_answer(chan->cdr);
429                 return res;
430                 break;
431         case AST_STATE_UP:
432                 break;
433         }
434         return 0;
435 }
436
437 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
438 {
439         /* Wait for x amount of time on a file descriptor to have input.  */
440         struct timeval tv;
441         fd_set rfds, efds;
442         int res;
443         int x, max=-1;
444         int winner = -1;
445         
446         tv.tv_sec = *ms / 1000;
447         tv.tv_usec = (*ms % 1000) * 1000;
448         FD_ZERO(&rfds);
449         FD_ZERO(&efds);
450         for (x=0;x<n;x++) {
451                 if (fds[x] > -1) {
452                         FD_SET(fds[x], &rfds);
453                         FD_SET(fds[x], &efds);
454                         if (fds[x] > max)
455                                 max = fds[x];
456                 }
457         }
458         if (*ms >= 0) 
459                 res = select(max + 1, &rfds, NULL, &efds, &tv);
460         else
461                 res = select(max + 1, &rfds, NULL, &efds, NULL);
462
463         if (res < 0) {
464                 /* Simulate a timeout if we were interrupted */
465                 if (errno != EINTR)
466                         *ms = -1;
467                 else
468                         *ms = 0;
469                 return -1;
470         }
471
472         for (x=0;x<n;x++) {
473                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
474                         if (exception)
475                                 *exception = FD_ISSET(fds[x], &efds);
476                         winner = fds[x];
477                 }
478         }
479         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
480         return winner;
481 }
482
483 static int ast_do_masquerade(struct ast_channel *original);
484
485 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
486         int *exception, int *outfd, int *ms)
487 {
488         /* Wait for x amount of time on a file descriptor to have input.  */
489         struct timeval tv;
490         fd_set rfds, efds;
491         int res;
492         int x, y, max=-1;
493         struct ast_channel *winner = NULL;
494         if (outfd)
495                 *outfd = -1;
496         if (exception)
497                 *exception = 0;
498         
499         /* Perform any pending masquerades */
500         for (x=0;x<n;x++) {
501                 if (c[x]->masq) {
502                         if (ast_do_masquerade(c[x])) {
503                                 ast_log(LOG_WARNING, "Masquerade failed\n");
504                                 *ms = -1;
505                                 return NULL;
506                         }
507                 }
508         }
509         
510         tv.tv_sec = *ms / 1000;
511         tv.tv_usec = (*ms % 1000) * 1000;
512         FD_ZERO(&rfds);
513         FD_ZERO(&efds);
514         for (x=0;x<n;x++) {
515                 for (y=0;y<AST_MAX_FDS;y++) {
516                         if (c[x]->fds[y] > 0) {
517                                 FD_SET(c[x]->fds[y], &rfds);
518                                 FD_SET(c[x]->fds[y], &efds);
519                                 if (c[x]->fds[y] > max)
520                                         max = c[x]->fds[y];
521                         }
522                 }
523                 CHECK_BLOCKING(c[x]);
524         }
525         for (x=0;x<nfds; x++) {
526                 FD_SET(fds[x], &rfds);
527                 FD_SET(fds[x], &efds);
528                 if (fds[x] > max)
529                         max = fds[x];
530         }
531         if (*ms >= 0) 
532                 res = select(max + 1, &rfds, NULL, &efds, &tv);
533         else
534                 res = select(max + 1, &rfds, NULL, &efds, NULL);
535
536         if (res < 0) {
537                 for (x=0;x<n;x++) 
538                         c[x]->blocking = 0;
539                 /* Simulate a timeout if we were interrupted */
540                 if (errno != EINTR)
541                         *ms = -1;
542                 else {
543                         /* Just an interrupt */
544 #if 0
545                         *ms = 0;
546 #endif                  
547                 }
548                 return NULL;
549         }
550
551         for (x=0;x<n;x++) {
552                 c[x]->blocking = 0;
553                 for (y=0;y<AST_MAX_FDS;y++) {
554                         if (c[x]->fds[y] > -1) {
555                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
556                                         /* Set exception flag if appropriate */
557                                         if (FD_ISSET(c[x]->fds[y], &efds))
558                                                 c[x]->exception = 1;
559                                         c[x]->fdno = y;
560                                         winner = c[x];
561                                 }
562                         }
563                 }
564         }
565         for (x=0;x<nfds;x++) {
566                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
567                         if (outfd)
568                                 *outfd = fds[x];
569                         if (FD_ISSET(fds[x], &efds) && exception)
570                                 *exception = 1;
571                         winner = NULL;
572                 }
573         }
574         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
575         return winner;
576 }
577
578 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
579 {
580         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
581 }
582
583 int ast_waitfor(struct ast_channel *c, int ms)
584 {
585         struct ast_channel *chan;
586         int oldms = ms;
587         chan = ast_waitfor_n(&c, 1, &ms);
588         if (ms < 0) {
589                 if (oldms < 0)
590                         return 0;
591                 else
592                         return -1;
593         }
594         return ms;
595 }
596
597 char ast_waitfordigit(struct ast_channel *c, int ms)
598 {
599         struct ast_frame *f;
600         char result = 0;
601         /* Stop if we're a zombie or need a soft hangup */
602         if (c->zombie || ast_check_hangup(c)) 
603                 return -1;
604         /* Wait for a digit, no more than ms milliseconds total. */
605         while(ms && !result) {
606                 ms = ast_waitfor(c, ms);
607                 if (ms < 0) /* Error */
608                         result = -1; 
609                 else if (ms > 0) {
610                         /* Read something */
611                         f = ast_read(c);
612                         if (f) {
613                                 if (f->frametype == AST_FRAME_DTMF) 
614                                         result = f->subclass;
615                                 ast_frfree(f);
616                         } else
617                                 result = -1;
618                 }
619         }
620         return result;
621 }
622
623 struct ast_frame *ast_read(struct ast_channel *chan)
624 {
625         struct ast_frame *f = NULL;
626         static struct ast_frame null_frame = 
627         {
628                 AST_FRAME_NULL,
629         };
630         
631         pthread_mutex_lock(&chan->lock);
632         if (chan->masq) {
633                 if (ast_do_masquerade(chan)) {
634                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
635                         f = NULL;
636                 } else
637                         f =  &null_frame;
638                 pthread_mutex_unlock(&chan->lock);
639                 return f;
640         }
641
642         /* Stop if we're a zombie or need a soft hangup */
643         if (chan->zombie || ast_check_hangup(chan)) {
644                 pthread_mutex_unlock(&chan->lock);
645                 return NULL;
646         }
647         
648         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
649                 /* We have DTMF that has been deferred.  Return it now */
650                 chan->dtmff.frametype = AST_FRAME_DTMF;
651                 chan->dtmff.subclass = chan->dtmfq[0];
652                 /* Drop first digit */
653                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
654                 pthread_mutex_unlock(&chan->lock);
655                 return &chan->dtmff;
656         }
657         
658         chan->blocker = pthread_self();
659         if (chan->exception) {
660                 if (chan->pvt->exception) 
661                         f = chan->pvt->exception(chan);
662                 else
663                         ast_log(LOG_WARNING, "Exception flag set, but no exception handler\n");
664                 /* Clear the exception flag */
665                 chan->exception = 0;
666         } else
667         if (chan->pvt->read)
668                 f = chan->pvt->read(chan);
669         else
670                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan);
671         if (f && (f->frametype == AST_FRAME_VOICE)) {
672                 if (chan->pvt->readtrans) {
673                         f = ast_translate(chan->pvt->readtrans, f, 1);
674                         if (!f)
675                                 f = &null_frame;
676                 }
677         }
678         /* Make sure we always return NULL in the future */
679         if (!f) {
680                 chan->softhangup = 1;
681                 /* End the CDR if appropriate */
682                 if (chan->cdr)
683                         ast_cdr_end(chan->cdr);
684         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
685                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
686                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
687                 else
688                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
689                 f = &null_frame;
690         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
691                 /* Answer the CDR */
692                 ast_cdr_answer(chan->cdr);
693         }
694         pthread_mutex_unlock(&chan->lock);
695
696         return f;
697 }
698
699 int ast_indicate(struct ast_channel *chan, int condition)
700 {
701         int res = -1;
702         /* Stop if we're a zombie or need a soft hangup */
703         if (chan->zombie || ast_check_hangup(chan)) 
704                 return -1;
705         if (chan->pvt->indicate) {
706                 res = chan->pvt->indicate(chan, condition);
707                 if (res)
708                         ast_log(LOG_WARNING, "Driver for channel '%s' failed to indicate condition %d\n", chan->name, condition);
709         } else
710                 ast_log(LOG_WARNING, "Driver for channel '%s' does not support indication\n", chan->name);
711         return res;
712 }
713
714 int ast_recvchar(struct ast_channel *chan, int timeout)
715 {
716         int res,ourto,c;
717         struct ast_frame *f;
718         
719         ourto = timeout;
720         for(;;)
721            {
722                 if (ast_check_hangup(chan)) return -1;
723                 res = ast_waitfor(chan,ourto);
724                 if (res <= 0) /* if timeout */
725                    {
726                         return 0;
727                    }
728                 ourto = res;
729                 f = ast_read(chan);
730                 if (f == NULL) return -1; /* if hangup */
731                 if ((f->frametype == AST_FRAME_CONTROL) &&
732                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
733                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
734                    {
735                         c = *((char *)f->data);  /* get the data */
736                         ast_frfree(f);
737                         return(c);
738                    }
739                 ast_frfree(f);
740         }
741 }
742
743 int ast_sendtext(struct ast_channel *chan, char *text)
744 {
745         int res = 0;
746         /* Stop if we're a zombie or need a soft hangup */
747         if (chan->zombie || ast_check_hangup(chan)) 
748                 return -1;
749         CHECK_BLOCKING(chan);
750         if (chan->pvt->send_text)
751                 res = chan->pvt->send_text(chan, text);
752         chan->blocking = 0;
753         return res;
754 }
755
756 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
757 {
758         int res = -1;
759         struct ast_frame *f;
760         /* Stop if we're a zombie or need a soft hangup */
761         if (chan->zombie || ast_check_hangup(chan)) 
762                 return -1;
763         /* Handle any pending masquerades */
764         if (chan->masq) {
765                 if (ast_do_masquerade(chan)) {
766                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
767                         return -1;
768                 }
769         }
770         if (chan->masqr)
771                 return 0;
772         CHECK_BLOCKING(chan);
773         switch(fr->frametype) {
774         case AST_FRAME_CONTROL:
775                 /* XXX Interpret control frames XXX */
776                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
777                 break;
778         case AST_FRAME_DTMF:
779                 if (chan->pvt->send_digit)
780                         res = chan->pvt->send_digit(chan, fr->subclass);
781                 break;
782         case AST_FRAME_TEXT:
783                 if (chan->pvt->send_text)
784                         res = chan->pvt->send_text(chan, (char *) fr->data);
785                 break;
786         default:
787                 if (chan->pvt->write) {
788                         if (chan->pvt->writetrans) {
789                                 f = ast_translate(chan->pvt->writetrans, fr, 1);
790                         } else
791                                 f = fr;
792                         if (f)  
793                                 res = chan->pvt->write(chan, f);
794                         else
795                                 res = 0;
796                 }
797         }
798         chan->blocking = 0;
799         return res;
800 }
801
802 int ast_set_write_format(struct ast_channel *chan, int fmts)
803 {
804         int fmt;
805         int native;
806         int res;
807         
808         native = chan->nativeformats;
809         fmt = fmts;
810         
811         res = ast_translator_best_choice(&native, &fmt);
812         if (res < 0) {
813                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
814                 return -1;
815         }
816         
817         /* Now we have a good choice for both.  We'll write using our native format. */
818         chan->pvt->rawwriteformat = native;
819         /* User perspective is fmt */
820         chan->writeformat = fmt;
821         /* Free any write translation we have right now */
822         if (chan->pvt->writetrans)
823                 ast_translator_free_path(chan->pvt->writetrans);
824         /* Build a translation path from the user write format to the raw writing format */
825         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
826         if (option_debug)
827                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
828         return 0;
829 }
830
831 int ast_set_read_format(struct ast_channel *chan, int fmts)
832 {
833         int fmt;
834         int native;
835         int res;
836         
837         native = chan->nativeformats;
838         fmt = fmts;
839         /* Find a translation path from the native read format to one of the user's read formats */
840         res = ast_translator_best_choice(&fmt, &native);
841         if (res < 0) {
842                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
843                 return -1;
844         }
845         
846         /* Now we have a good choice for both.  We'll write using our native format. */
847         chan->pvt->rawreadformat = native;
848         /* User perspective is fmt */
849         chan->readformat = fmt;
850         /* Free any read translation we have right now */
851         if (chan->pvt->readtrans)
852                 ast_translator_free_path(chan->pvt->readtrans);
853         /* Build a translation path from the raw read format to the user reading format */
854         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
855         if (option_debug)
856                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
857         return 0;
858 }
859
860 struct ast_channel *ast_request(char *type, int format, void *data)
861 {
862         struct chanlist *chan;
863         struct ast_channel *c = NULL;
864         int capabilities;
865         int fmt;
866         int res;
867         if (PTHREAD_MUTEX_LOCK(&chlock)) {
868                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
869                 return NULL;
870         }
871         chan = backends;
872         while(chan) {
873                 if (!strcasecmp(type, chan->type)) {
874                         capabilities = chan->capabilities;
875                         fmt = format;
876                         res = ast_translator_best_choice(&fmt, &capabilities);
877                         if (res < 0) {
878                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
879                                 PTHREAD_MUTEX_UNLOCK(&chlock);
880                                 return NULL;
881                         }
882                         PTHREAD_MUTEX_UNLOCK(&chlock);
883                         if (chan->requester)
884                                 c = chan->requester(type, capabilities, data);
885                         return c;
886                 }
887                 chan = chan->next;
888         }
889         if (!chan)
890                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
891         PTHREAD_MUTEX_UNLOCK(&chlock);
892         return c;
893 }
894
895 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
896 {
897         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
898            If the remote end does not answer within the timeout, then do NOT hang up, but 
899            return anyway.  */
900         int res = -1;
901         /* Stop if we're a zombie or need a soft hangup */
902         pthread_mutex_lock(&chan->lock);
903         if (!chan->zombie && !ast_check_hangup(chan)) 
904                 if (chan->pvt->call)
905                         res = chan->pvt->call(chan, addr, timeout);
906         pthread_mutex_unlock(&chan->lock);
907         return res;
908 }
909
910 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
911 {
912         int pos=0;
913         int to = ftimeout;
914         char d;
915         /* Stop if we're a zombie or need a soft hangup */
916         if (c->zombie || ast_check_hangup(c)) 
917                 return -1;
918         if (!len)
919                 return -1;
920         do {
921                 if (c->streamid > -1) {
922                         d = ast_waitstream(c, AST_DIGIT_ANY);
923                         ast_stopstream(c);
924                         usleep(1000);
925                         if (!d)
926                                 d = ast_waitfordigit(c, to);
927                 } else {
928                         d = ast_waitfordigit(c, to);
929                 }
930                 if (d < 0)
931                         return -1;
932                 if (d == 0) {
933                         s[pos]='\0';
934                         return 1;
935                 }
936                 if (!strchr(enders, d))
937                         s[pos++] = d;
938                 if (strchr(enders, d) || (pos >= len)) {
939                         s[pos]='\0';
940                         return 0;
941                 }
942                 to = timeout;
943         } while(1);
944         /* Never reached */
945         return 0;
946 }
947
948 int ast_channel_supports_html(struct ast_channel *chan)
949 {
950         if (chan->pvt->send_html)
951                 return 1;
952         return 0;
953 }
954
955 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
956 {
957         if (chan->pvt->send_html)
958                 return chan->pvt->send_html(chan, subclass, data, datalen);
959         return -1;
960 }
961
962 int ast_channel_sendurl(struct ast_channel *chan, char *url)
963 {
964         if (chan->pvt->send_html)
965                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
966         return -1;
967 }
968
969 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
970 {
971         int peerf;
972         int chanf;
973         int res;
974         peerf = peer->nativeformats;
975         chanf = chan->nativeformats;
976         res = ast_translator_best_choice(&peerf, &chanf);
977         if (res < 0) {
978                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan, chan->nativeformats, peer, peer->nativeformats);
979                 return -1;
980         }
981         /* Set read format on channel */
982         res = ast_set_read_format(chan, peerf);
983         if (res < 0) {
984                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan, chanf);
985                 return -1;
986         }
987         /* Set write format on peer channel */
988         res = ast_set_write_format(peer, peerf);
989         if (res < 0) {
990                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer, peerf);
991                 return -1;
992         }
993         /* Now we go the other way */
994         peerf = peer->nativeformats;
995         chanf = chan->nativeformats;
996         res = ast_translator_best_choice(&chanf, &peerf);
997         if (res < 0) {
998                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer, peer->nativeformats, chan, chan->nativeformats);
999                 return -1;
1000         }
1001         /* Set writeformat on channel */
1002         res = ast_set_write_format(chan, chanf);
1003         if (res < 0) {
1004                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan, chanf);
1005                 return -1;
1006         }
1007         /* Set read format on peer channel */
1008         res = ast_set_read_format(peer, chanf);
1009         if (res < 0) {
1010                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer, peerf);
1011                 return -1;
1012         }
1013         return 0;
1014 }
1015
1016 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1017 {
1018         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1019                 clone->name, original->name);
1020         if (original->masq) {
1021                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1022                         original->masq->name, original->name);
1023                 return -1;
1024         }
1025         if (clone->masqr) {
1026                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1027                         clone->name, clone->masqr->name);
1028                 return -1;
1029         }
1030         original->masq = clone;
1031         clone->masqr = original;
1032         return 0;
1033 }
1034
1035 static int ast_do_masquerade(struct ast_channel *original)
1036 {
1037         int x;
1038         int res=0;
1039         char *tmp;
1040         struct ast_channel_pvt *p;
1041         struct ast_channel *clone = original->masq;
1042         int rformat = original->readformat;
1043         int wformat = original->writeformat;
1044         
1045 #if 0
1046         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1047                 clone->name, clone->state, original->name, original->state);
1048 #endif
1049         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1050            the clone channel into the original channel.  Start by killing off the original
1051            channel's backend.   I'm not sure we're going to keep this function, because 
1052            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1053
1054         /* Having remembered the original read/write formats, we turn off any translation on either
1055            one */
1056         free_translation(clone);
1057         free_translation(original);
1058
1059         /* We need the clone's lock, too */
1060         pthread_mutex_lock(&clone->lock);
1061
1062         /* Unlink the masquerade */
1063         original->masq = NULL;
1064         clone->masqr = NULL;
1065                 
1066         /* Copy the name from the clone channel */
1067         strncpy(original->name, clone->name, sizeof(original->name)-1);
1068
1069         /* Mangle the name of the clone channel */
1070         strncat(clone->name, "<MASQ>", sizeof(clone->name));
1071
1072         /* Swap the guts */     
1073         p = original->pvt;
1074         original->pvt = clone->pvt;
1075         clone->pvt = p;
1076         
1077         clone->softhangup = 1;
1078
1079
1080         if (clone->pvt->fixup){
1081                 res = clone->pvt->fixup(original, clone);
1082                 if (res) 
1083                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1084         }
1085
1086         /* Start by disconnecting the original's physical side */
1087         if (clone->pvt->hangup)
1088                 res = clone->pvt->hangup(clone);
1089         if (res) {
1090                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1091                 pthread_mutex_unlock(&clone->lock);
1092                 return -1;
1093         }
1094         
1095         /* Mangle the name of the clone channel */
1096         snprintf(clone->name, sizeof(clone->name), "%s<ZOMBIE>", original->name);
1097
1098         /* Keep the same language.  */
1099         /* Update the type. */
1100         original->type = clone->type;
1101         /* Copy the FD's */
1102         for (x=0;x<AST_MAX_FDS;x++)
1103                 original->fds[x] = clone->fds[x];
1104         /* Presense of ADSI capable CPE follows clone */
1105         original->adsicpe = clone->adsicpe;
1106         /* Bridge remains the same */
1107         /* CDR fields remain the same */
1108         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1109         /* Application and data remain the same */
1110         /* Clone exception  becomes real one, as with fdno */
1111         original->exception = clone->exception;
1112         original->fdno = clone->fdno;
1113         /* Schedule context remains the same */
1114         /* Stream stuff stays the same */
1115         /* Keep the original state.  The fixup code will need to work with it most likely */
1116
1117         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1118            fields back into the defunct 'clone' so that they will be freed when
1119            ast_frfree is eventually called */
1120         tmp = original->dnid;
1121         original->dnid = clone->dnid;
1122         clone->dnid = tmp;
1123         
1124         tmp = original->callerid;
1125         original->callerid = clone->callerid;
1126         clone->callerid = tmp;
1127         
1128         /* Our native formats are different now */
1129         original->nativeformats = clone->nativeformats;
1130         
1131         /* Context, extension, priority, app data, jump table,  remain the same */
1132         /* pvt switches.  pbx stays the same, as does next */
1133         
1134         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1135            a zombie so nothing tries to touch it.  If it's already been marked as a
1136            zombie, then free it now (since it already is considered invalid). */
1137         if (clone->zombie) {
1138                 pthread_mutex_unlock(&clone->lock);
1139                 ast_channel_free(clone);
1140         } else {
1141                 clone->zombie=1;
1142                 pthread_mutex_unlock(&clone->lock);
1143         }
1144         /* Set the write format */
1145         ast_set_write_format(original, wformat);
1146
1147         /* Set the read format */
1148         ast_set_read_format(original, rformat);
1149
1150         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1151
1152         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1153            can fix up everything as best as possible */
1154         if (original->pvt->fixup) {
1155                 res = original->pvt->fixup(clone, original);
1156                 if (res) {
1157                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1158                                 original->type, original->name);
1159                         return -1;
1160                 }
1161         } else
1162                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1163                         original->type, original->name);
1164         /* Signal any blocker */
1165         if (original->blocking)
1166                 pthread_kill(original->blocker, SIGURG);
1167         ast_log(LOG_DEBUG, "Done Masquerading %s(%d) into the structure of %s(%d)\n",
1168                 clone->name, clone->state, original->name, original->state);
1169         return 0;
1170 }
1171
1172 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1173 {
1174         /* Copy voice back and forth between the two channels.  Give the peer
1175            the ability to transfer calls with '#<extension' syntax. */
1176         struct ast_channel *cs[3];
1177         int to = -1;
1178         struct ast_frame *f;
1179         struct ast_channel *who = NULL;
1180         int res;
1181         int nativefailed=0;
1182         /* Stop if we're a zombie or need a soft hangup */
1183         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1184                 return -1;
1185         if (c0->bridge) {
1186                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1187                         c0->name, c0->bridge->name);
1188                 return -1;
1189         }
1190         if (c1->bridge) {
1191                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1192                         c1->name, c1->bridge->name);
1193                 return -1;
1194         }
1195         
1196         /* Keep track of bridge */
1197         c0->bridge = c1;
1198         c1->bridge = c0;
1199         cs[0] = c0;
1200         cs[1] = c1;
1201         for (/* ever */;;) {
1202                 /* Stop if we're a zombie or need a soft hangup */
1203                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1204                         *fo = NULL;
1205                         if (who) *rc = who;
1206                         res = 0;
1207                         break;
1208                 }
1209                 if (c0->pvt->bridge && 
1210                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1211                                 /* Looks like they share a bridge code */
1212                         if (option_verbose > 2) 
1213                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
1214                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1215                                 c0->bridge = NULL;
1216                                 c1->bridge = NULL;
1217                                 return 0;
1218                         }
1219                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1220                            my not wanting to bridge */
1221                         if ((res != -2) && (res != -3))
1222                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1223                         if (res != -3) nativefailed++;
1224                 }
1225         
1226                         
1227                 if ((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) {
1228                         if (ast_channel_make_compatible(c0, c1)) {
1229                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1230                                 return -1;
1231                         }
1232                 }
1233                 who = ast_waitfor_n(cs, 2, &to);
1234                 if (!who) {
1235                         ast_log(LOG_WARNING, "Nobody there??\n"); 
1236                         continue;
1237                 }
1238                 f = ast_read(who);
1239                 if (!f) {
1240                         *fo = NULL;
1241                         *rc = who;
1242                         res = 0;
1243                         break;
1244                 }
1245                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1246                         *fo = f;
1247                         *rc = who;
1248                         res =  0;
1249                         break;
1250                 }
1251                 if ((f->frametype == AST_FRAME_VOICE) ||
1252                         (f->frametype == AST_FRAME_TEXT) ||
1253                         (f->frametype == AST_FRAME_VIDEO) || 
1254                         (f->frametype == AST_FRAME_IMAGE) ||
1255                         (f->frametype == AST_FRAME_DTMF)) {
1256                         if ((f->frametype == AST_FRAME_DTMF) && 
1257                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1258                                 if ((who == c0)) {
1259                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1260                                                 *rc = c0;
1261                                                 *fo = f;
1262                                                 /* Take out of conference mode */
1263                                                 res = 0;
1264                                                 break;
1265                                         } else 
1266                                                 goto tackygoto;
1267                                 } else
1268                                 if ((who == c1)) {
1269                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1270                                                 *rc = c1;
1271                                                 *fo = f;
1272                                                 res =  0;
1273                                                 break;
1274                                         } else
1275                                                 goto tackygoto;
1276                                 }
1277                         } else {
1278 #if 0
1279                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1280                                 if (who == last) 
1281                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1282                                 last = who;
1283 #endif
1284 tackygoto:
1285                                 if (who == c0) 
1286                                         ast_write(c1, f);
1287                                 else 
1288                                         ast_write(c0, f);
1289                         }
1290                         ast_frfree(f);
1291                 } else
1292                         ast_frfree(f);
1293                 /* Swap who gets priority */
1294                 cs[2] = cs[0];
1295                 cs[0] = cs[1];
1296                 cs[1] = cs[2];
1297         }
1298         c0->bridge = NULL;
1299         c1->bridge = NULL;
1300         return res;
1301 }
1302
1303 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1304 {
1305         int res;
1306         if (chan->pvt->setoption) {
1307                 res = chan->pvt->setoption(chan, option, data, datalen);
1308                 if (res < 0)
1309                         return res;
1310         } else {
1311                 errno = ENOSYS;
1312                 return -1;
1313         }
1314         if (block) {
1315                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1316                    intermediate packets. XXX */
1317                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1318                 return -1;
1319         }
1320         return 0;
1321 }
1322