b251c0bc429f0f31eeb132ebd24d0c493578cf48
[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->hidden_callerid)
307                 free(chan->hidden_callerid);
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                         *ms = 0;
544                 return NULL;
545         }
546
547         for (x=0;x<n;x++) {
548                 c[x]->blocking = 0;
549                 for (y=0;y<AST_MAX_FDS;y++) {
550                         if (c[x]->fds[y] > -1) {
551                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
552                                         /* Set exception flag if appropriate */
553                                         if (FD_ISSET(c[x]->fds[y], &efds))
554                                                 c[x]->exception = 1;
555                                         c[x]->fdno = y;
556                                         winner = c[x];
557                                 }
558                         }
559                 }
560         }
561         for (x=0;x<nfds;x++) {
562                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
563                         if (outfd)
564                                 *outfd = fds[x];
565                         if (FD_ISSET(fds[x], &efds) && exception)
566                                 *exception = 1;
567                         winner = NULL;
568                 }
569         }
570         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
571         return winner;
572 }
573
574 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
575 {
576         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
577 }
578
579 int ast_waitfor(struct ast_channel *c, int ms)
580 {
581         struct ast_channel *chan;
582         int oldms = ms;
583         chan = ast_waitfor_n(&c, 1, &ms);
584         if (ms < 0) {
585                 if (oldms < 0)
586                         return 0;
587                 else
588                         return -1;
589         }
590         return ms;
591 }
592
593 char ast_waitfordigit(struct ast_channel *c, int ms)
594 {
595         struct ast_frame *f;
596         char result = 0;
597         /* Stop if we're a zombie or need a soft hangup */
598         if (c->zombie || ast_check_hangup(c)) 
599                 return -1;
600         /* Wait for a digit, no more than ms milliseconds total. */
601         while(ms && !result) {
602                 ms = ast_waitfor(c, ms);
603                 if (ms < 0) /* Error */
604                         result = -1; 
605                 else if (ms > 0) {
606                         /* Read something */
607                         f = ast_read(c);
608                         if (f) {
609                                 if (f->frametype == AST_FRAME_DTMF) 
610                                         result = f->subclass;
611                                 ast_frfree(f);
612                         } else
613                                 result = -1;
614                 }
615         }
616         return result;
617 }
618
619 struct ast_frame *ast_read(struct ast_channel *chan)
620 {
621         struct ast_frame *f = NULL;
622         static struct ast_frame null_frame = 
623         {
624                 AST_FRAME_NULL,
625         };
626         
627         pthread_mutex_lock(&chan->lock);
628         if (chan->masq) {
629                 if (ast_do_masquerade(chan)) {
630                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
631                         f = NULL;
632                 } else
633                         f =  &null_frame;
634                 pthread_mutex_unlock(&chan->lock);
635                 return f;
636         }
637
638         /* Stop if we're a zombie or need a soft hangup */
639         if (chan->zombie || ast_check_hangup(chan)) {
640                 pthread_mutex_unlock(&chan->lock);
641                 return NULL;
642         }
643         
644         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
645                 /* We have DTMF that has been deferred.  Return it now */
646                 chan->dtmff.frametype = AST_FRAME_DTMF;
647                 chan->dtmff.subclass = chan->dtmfq[0];
648                 /* Drop first digit */
649                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
650                 pthread_mutex_unlock(&chan->lock);
651                 return &chan->dtmff;
652         }
653         
654         chan->blocker = pthread_self();
655         if (chan->exception) {
656                 if (chan->pvt->exception) 
657                         f = chan->pvt->exception(chan);
658                 else
659                         ast_log(LOG_WARNING, "Exception flag set, but no exception handler\n");
660                 /* Clear the exception flag */
661                 chan->exception = 0;
662         } else
663         if (chan->pvt->read)
664                 f = chan->pvt->read(chan);
665         else
666                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan);
667         if (f && (f->frametype == AST_FRAME_VOICE)) {
668                 if (chan->pvt->readtrans) {
669                         f = ast_translate(chan->pvt->readtrans, f, 1);
670                         if (!f)
671                                 f = &null_frame;
672                 }
673         }
674         /* Make sure we always return NULL in the future */
675         if (!f) {
676                 chan->softhangup = 1;
677                 /* End the CDR if appropriate */
678                 if (chan->cdr)
679                         ast_cdr_end(chan->cdr);
680         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
681                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
682                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
683                 else
684                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
685                 f = &null_frame;
686         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
687                 /* Answer the CDR */
688                 ast_cdr_answer(chan->cdr);
689         }
690         pthread_mutex_unlock(&chan->lock);
691
692         return f;
693 }
694
695 int ast_indicate(struct ast_channel *chan, int condition)
696 {
697         int res = -1;
698         /* Stop if we're a zombie or need a soft hangup */
699         if (chan->zombie || ast_check_hangup(chan)) 
700                 return -1;
701         if (chan->pvt->indicate) {
702                 res = chan->pvt->indicate(chan, condition);
703                 if (res)
704                         ast_log(LOG_WARNING, "Driver for channel '%s' failed to indicate condition %d\n", chan->name, condition);
705         } else
706                 ast_log(LOG_WARNING, "Driver for channel '%s' does not support indication\n", chan->name);
707         return res;
708 }
709
710 int ast_recvchar(struct ast_channel *chan, int timeout)
711 {
712         int res,ourto,c;
713         struct ast_frame *f;
714         
715         ourto = timeout;
716         for(;;)
717            {
718                 if (ast_check_hangup(chan)) return -1;
719                 res = ast_waitfor(chan,ourto);
720                 if (res <= 0) /* if timeout */
721                    {
722                         return 0;
723                    }
724                 ourto = res;
725                 f = ast_read(chan);
726                 if (f == NULL) return -1; /* if hangup */
727                 if ((f->frametype == AST_FRAME_CONTROL) &&
728                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
729                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
730                    {
731                         c = *((char *)f->data);  /* get the data */
732                         ast_frfree(f);
733                         return(c);
734                    }
735                 ast_frfree(f);
736         }
737 }
738
739 int ast_sendtext(struct ast_channel *chan, char *text)
740 {
741         int res = 0;
742         /* Stop if we're a zombie or need a soft hangup */
743         if (chan->zombie || ast_check_hangup(chan)) 
744                 return -1;
745         CHECK_BLOCKING(chan);
746         if (chan->pvt->send_text)
747                 res = chan->pvt->send_text(chan, text);
748         chan->blocking = 0;
749         return res;
750 }
751
752 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
753 {
754         int res = -1;
755         struct ast_frame *f;
756         /* Stop if we're a zombie or need a soft hangup */
757         if (chan->zombie || ast_check_hangup(chan)) 
758                 return -1;
759         /* Handle any pending masquerades */
760         if (chan->masq) {
761                 if (ast_do_masquerade(chan)) {
762                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
763                         return -1;
764                 }
765         }
766         if (chan->masqr)
767                 return 0;
768         CHECK_BLOCKING(chan);
769         switch(fr->frametype) {
770         case AST_FRAME_CONTROL:
771                 /* XXX Interpret control frames XXX */
772                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
773                 break;
774         case AST_FRAME_DTMF:
775                 if (chan->pvt->send_digit)
776                         res = chan->pvt->send_digit(chan, fr->subclass);
777                 break;
778         case AST_FRAME_TEXT:
779                 if (chan->pvt->send_text)
780                         res = chan->pvt->send_text(chan, (char *) fr->data);
781                 break;
782         default:
783                 if (chan->pvt->write) {
784                         if (chan->pvt->writetrans) {
785                                 f = ast_translate(chan->pvt->writetrans, fr, 1);
786                         } else
787                                 f = fr;
788                         if (f)  
789                                 res = chan->pvt->write(chan, f);
790                         else
791                                 res = 0;
792                 }
793         }
794         chan->blocking = 0;
795         return res;
796 }
797
798 int ast_set_write_format(struct ast_channel *chan, int fmts)
799 {
800         int fmt;
801         int native;
802         int res;
803         
804         native = chan->nativeformats;
805         fmt = fmts;
806         
807         res = ast_translator_best_choice(&native, &fmt);
808         if (res < 0) {
809                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
810                 return -1;
811         }
812         
813         /* Now we have a good choice for both.  We'll write using our native format. */
814         chan->pvt->rawwriteformat = native;
815         /* User perspective is fmt */
816         chan->writeformat = fmt;
817         /* Free any write translation we have right now */
818         if (chan->pvt->writetrans)
819                 ast_translator_free_path(chan->pvt->writetrans);
820         /* Build a translation path from the user write format to the raw writing format */
821         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
822         if (option_debug)
823                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
824         return 0;
825 }
826
827 int ast_set_read_format(struct ast_channel *chan, int fmts)
828 {
829         int fmt;
830         int native;
831         int res;
832         
833         native = chan->nativeformats;
834         fmt = fmts;
835         /* Find a translation path from the native read format to one of the user's read formats */
836         res = ast_translator_best_choice(&fmt, &native);
837         if (res < 0) {
838                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
839                 return -1;
840         }
841         
842         /* Now we have a good choice for both.  We'll write using our native format. */
843         chan->pvt->rawreadformat = native;
844         /* User perspective is fmt */
845         chan->readformat = fmt;
846         /* Free any read translation we have right now */
847         if (chan->pvt->readtrans)
848                 ast_translator_free_path(chan->pvt->readtrans);
849         /* Build a translation path from the raw read format to the user reading format */
850         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
851         if (option_debug)
852                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
853         return 0;
854 }
855
856 struct ast_channel *ast_request(char *type, int format, void *data)
857 {
858         struct chanlist *chan;
859         struct ast_channel *c = NULL;
860         int capabilities;
861         int fmt;
862         int res;
863         if (PTHREAD_MUTEX_LOCK(&chlock)) {
864                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
865                 return NULL;
866         }
867         chan = backends;
868         while(chan) {
869                 if (!strcasecmp(type, chan->type)) {
870                         capabilities = chan->capabilities;
871                         fmt = format;
872                         res = ast_translator_best_choice(&fmt, &capabilities);
873                         if (res < 0) {
874                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
875                                 PTHREAD_MUTEX_UNLOCK(&chlock);
876                                 return NULL;
877                         }
878                         PTHREAD_MUTEX_UNLOCK(&chlock);
879                         if (chan->requester)
880                                 c = chan->requester(type, capabilities, data);
881                         return c;
882                 }
883                 chan = chan->next;
884         }
885         if (!chan)
886                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
887         PTHREAD_MUTEX_UNLOCK(&chlock);
888         return c;
889 }
890
891 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
892 {
893         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
894            If the remote end does not answer within the timeout, then do NOT hang up, but 
895            return anyway.  */
896         int res = -1;
897         /* Stop if we're a zombie or need a soft hangup */
898         pthread_mutex_lock(&chan->lock);
899         if (!chan->zombie && !ast_check_hangup(chan)) 
900                 if (chan->pvt->call)
901                         res = chan->pvt->call(chan, addr, timeout);
902         pthread_mutex_unlock(&chan->lock);
903         return res;
904 }
905
906 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
907 {
908         int pos=0;
909         int to = ftimeout;
910         char d;
911         /* Stop if we're a zombie or need a soft hangup */
912         if (c->zombie || ast_check_hangup(c)) 
913                 return -1;
914         if (!len)
915                 return -1;
916         do {
917                 if (c->streamid > -1) {
918                         d = ast_waitstream(c, AST_DIGIT_ANY);
919                         ast_stopstream(c);
920                         usleep(1000);
921                         if (!d)
922                                 d = ast_waitfordigit(c, to);
923                 } else {
924                         d = ast_waitfordigit(c, to);
925                 }
926                 if (d < 0)
927                         return -1;
928                 if (d == 0) {
929                         s[pos]='\0';
930                         return 1;
931                 }
932                 if (!strchr(enders, d))
933                         s[pos++] = d;
934                 if (strchr(enders, d) || (pos >= len - 1)) {
935                         s[pos]='\0';
936                         return 0;
937                 }
938                 to = timeout;
939         } while(1);
940         /* Never reached */
941         return 0;
942 }
943
944 int ast_channel_supports_html(struct ast_channel *chan)
945 {
946         if (chan->pvt->send_html)
947                 return 1;
948         return 0;
949 }
950
951 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
952 {
953         if (chan->pvt->send_html)
954                 return chan->pvt->send_html(chan, subclass, data, datalen);
955         return -1;
956 }
957
958 int ast_channel_sendurl(struct ast_channel *chan, char *url)
959 {
960         if (chan->pvt->send_html)
961                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
962         return -1;
963 }
964
965 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
966 {
967         int peerf;
968         int chanf;
969         int res;
970         peerf = peer->nativeformats;
971         chanf = chan->nativeformats;
972         res = ast_translator_best_choice(&peerf, &chanf);
973         if (res < 0) {
974                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan, chan->nativeformats, peer, peer->nativeformats);
975                 return -1;
976         }
977         /* Set read format on channel */
978         res = ast_set_read_format(chan, peerf);
979         if (res < 0) {
980                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan, chanf);
981                 return -1;
982         }
983         /* Set write format on peer channel */
984         res = ast_set_write_format(peer, peerf);
985         if (res < 0) {
986                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer, peerf);
987                 return -1;
988         }
989         /* Now we go the other way */
990         peerf = peer->nativeformats;
991         chanf = chan->nativeformats;
992         res = ast_translator_best_choice(&chanf, &peerf);
993         if (res < 0) {
994                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer, peer->nativeformats, chan, chan->nativeformats);
995                 return -1;
996         }
997         /* Set writeformat on channel */
998         res = ast_set_write_format(chan, chanf);
999         if (res < 0) {
1000                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan, chanf);
1001                 return -1;
1002         }
1003         /* Set read format on peer channel */
1004         res = ast_set_read_format(peer, chanf);
1005         if (res < 0) {
1006                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer, peerf);
1007                 return -1;
1008         }
1009         return 0;
1010 }
1011
1012 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1013 {
1014         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1015                 clone->name, original->name);
1016         if (original->masq) {
1017                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1018                         original->masq->name, original->name);
1019                 return -1;
1020         }
1021         if (clone->masqr) {
1022                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1023                         clone->name, clone->masqr->name);
1024                 return -1;
1025         }
1026         original->masq = clone;
1027         clone->masqr = original;
1028         return 0;
1029 }
1030
1031 static int ast_do_masquerade(struct ast_channel *original)
1032 {
1033         int x;
1034         int res=0;
1035         char *tmp;
1036         struct ast_channel_pvt *p;
1037         struct ast_channel *clone = original->masq;
1038         int rformat = original->readformat;
1039         int wformat = original->writeformat;
1040         
1041 #if 0
1042         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1043                 clone->name, clone->state, original->name, original->state);
1044 #endif
1045         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1046            the clone channel into the original channel.  Start by killing off the original
1047            channel's backend.   I'm not sure we're going to keep this function, because 
1048            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1049
1050         /* Having remembered the original read/write formats, we turn off any translation on either
1051            one */
1052         free_translation(clone);
1053         free_translation(original);
1054
1055         /* We need the clone's lock, too */
1056         pthread_mutex_lock(&clone->lock);
1057
1058         /* Unlink the masquerade */
1059         original->masq = NULL;
1060         clone->masqr = NULL;
1061                 
1062         /* Copy the name from the clone channel */
1063         strncpy(original->name, clone->name, sizeof(original->name)-1);
1064
1065         /* Mangle the name of the clone channel */
1066         strncat(clone->name, "<MASQ>", sizeof(clone->name));
1067
1068         /* Swap the guts */     
1069         p = original->pvt;
1070         original->pvt = clone->pvt;
1071         clone->pvt = p;
1072         
1073         clone->softhangup = 1;
1074
1075
1076         if (clone->pvt->fixup){
1077                 res = clone->pvt->fixup(original, clone);
1078                 if (res) 
1079                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1080         }
1081
1082         /* Start by disconnecting the original's physical side */
1083         if (clone->pvt->hangup)
1084                 res = clone->pvt->hangup(clone);
1085         if (res) {
1086                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1087                 pthread_mutex_unlock(&clone->lock);
1088                 return -1;
1089         }
1090         
1091         /* Mangle the name of the clone channel */
1092         snprintf(clone->name, sizeof(clone->name), "%s<ZOMBIE>", original->name);
1093
1094         /* Keep the same language.  */
1095         /* Update the type. */
1096         original->type = clone->type;
1097         /* Copy the FD's */
1098         for (x=0;x<AST_MAX_FDS;x++)
1099                 original->fds[x] = clone->fds[x];
1100         /* Presense of ADSI capable CPE follows clone */
1101         original->adsicpe = clone->adsicpe;
1102         /* Bridge remains the same */
1103         /* CDR fields remain the same */
1104         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1105         /* Application and data remain the same */
1106         /* Clone exception  becomes real one, as with fdno */
1107         original->exception = clone->exception;
1108         original->fdno = clone->fdno;
1109         /* Schedule context remains the same */
1110         /* Stream stuff stays the same */
1111         /* Keep the original state.  The fixup code will need to work with it most likely */
1112
1113         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1114            fields back into the defunct 'clone' so that they will be freed when
1115            ast_frfree is eventually called */
1116         tmp = original->dnid;
1117         original->dnid = clone->dnid;
1118         clone->dnid = tmp;
1119         
1120         tmp = original->callerid;
1121         original->callerid = clone->callerid;
1122         clone->callerid = tmp;
1123         
1124         /* Our native formats are different now */
1125         original->nativeformats = clone->nativeformats;
1126         
1127         /* Context, extension, priority, app data, jump table,  remain the same */
1128         /* pvt switches.  pbx stays the same, as does next */
1129         
1130         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1131            a zombie so nothing tries to touch it.  If it's already been marked as a
1132            zombie, then free it now (since it already is considered invalid). */
1133         if (clone->zombie) {
1134                 pthread_mutex_unlock(&clone->lock);
1135                 ast_channel_free(clone);
1136         } else {
1137                 clone->zombie=1;
1138                 pthread_mutex_unlock(&clone->lock);
1139         }
1140         /* Set the write format */
1141         ast_set_write_format(original, wformat);
1142
1143         /* Set the read format */
1144         ast_set_read_format(original, rformat);
1145
1146         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1147
1148         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1149            can fix up everything as best as possible */
1150         if (original->pvt->fixup) {
1151                 res = original->pvt->fixup(clone, original);
1152                 if (res) {
1153                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1154                                 original->type, original->name);
1155                         return -1;
1156                 }
1157         } else
1158                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1159                         original->type, original->name);
1160         /* Signal any blocker */
1161         if (original->blocking)
1162                 pthread_kill(original->blocker, SIGURG);
1163         ast_log(LOG_DEBUG, "Done Masquerading %s(%d) into the structure of %s(%d)\n",
1164                 clone->name, clone->state, original->name, original->state);
1165         return 0;
1166 }
1167
1168 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1169 {
1170         /* Copy voice back and forth between the two channels.  Give the peer
1171            the ability to transfer calls with '#<extension' syntax. */
1172         struct ast_channel *cs[3];
1173         int to = -1;
1174         struct ast_frame *f;
1175         struct ast_channel *who = NULL;
1176         int res;
1177         int nativefailed=0;
1178         /* Stop if we're a zombie or need a soft hangup */
1179         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1180                 return -1;
1181         if (c0->bridge) {
1182                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1183                         c0->name, c0->bridge->name);
1184                 return -1;
1185         }
1186         if (c1->bridge) {
1187                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
1188                         c1->name, c1->bridge->name);
1189                 return -1;
1190         }
1191         
1192         /* Keep track of bridge */
1193         c0->bridge = c1;
1194         c1->bridge = c0;
1195         cs[0] = c0;
1196         cs[1] = c1;
1197         for (/* ever */;;) {
1198                 /* Stop if we're a zombie or need a soft hangup */
1199                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1200                         *fo = NULL;
1201                         if (who) *rc = who;
1202                         res = 0;
1203                         break;
1204                 }
1205                 if (c0->pvt->bridge && 
1206                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed) {
1207                                 /* Looks like they share a bridge code */
1208                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
1209                                 c0->bridge = NULL;
1210                                 c1->bridge = NULL;
1211                                 return 0;
1212                         }
1213                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
1214                            my not wanting to bridge */
1215                         if ((res != -2) && (res != -3))
1216                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
1217                         if (res != -3) nativefailed++;
1218                 }
1219         
1220                         
1221                 if ((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) {
1222                         if (ast_channel_make_compatible(c0, c1)) {
1223                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
1224                                 return -1;
1225                         }
1226                 }
1227                 who = ast_waitfor_n(cs, 2, &to);
1228                 if (!who) {
1229                         ast_log(LOG_WARNING, "Nobody there??\n"); 
1230                         continue;
1231                 }
1232                 f = ast_read(who);
1233                 if (!f) {
1234                         *fo = NULL;
1235                         *rc = who;
1236                         res = 0;
1237                         break;
1238                 }
1239                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1240                         *fo = f;
1241                         *rc = who;
1242                         res =  0;
1243                         break;
1244                 }
1245                 if ((f->frametype == AST_FRAME_VOICE) ||
1246                         (f->frametype == AST_FRAME_TEXT) ||
1247                         (f->frametype == AST_FRAME_VIDEO) || 
1248                         (f->frametype == AST_FRAME_IMAGE) ||
1249                         (f->frametype == AST_FRAME_DTMF)) {
1250                         if ((f->frametype == AST_FRAME_DTMF) && 
1251                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1252                                 if ((who == c0)) {
1253                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1254                                                 *rc = c0;
1255                                                 *fo = f;
1256                                                 /* Take out of conference mode */
1257                                                 res = 0;
1258                                                 break;
1259                                         } else 
1260                                                 goto tackygoto;
1261                                 } else
1262                                 if ((who == c1)) {
1263                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
1264                                                 *rc = c1;
1265                                                 *fo = f;
1266                                                 res =  0;
1267                                                 break;
1268                                         } else
1269                                                 goto tackygoto;
1270                                 }
1271                         } else {
1272 #if 0
1273                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1274                                 if (who == last) 
1275                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1276                                 last = who;
1277 #endif
1278 tackygoto:
1279                                 if (who == c0) 
1280                                         ast_write(c1, f);
1281                                 else 
1282                                         ast_write(c0, f);
1283                         }
1284                         ast_frfree(f);
1285                 } else
1286                         ast_frfree(f);
1287                 /* Swap who gets priority */
1288                 cs[2] = cs[0];
1289                 cs[0] = cs[1];
1290                 cs[1] = cs[2];
1291         }
1292         c0->bridge = NULL;
1293         c1->bridge = NULL;
1294         return res;
1295 }
1296
1297 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1298 {
1299         int res;
1300         if (chan->pvt->setoption) {
1301                 res = chan->pvt->setoption(chan, option, data, datalen);
1302                 if (res < 0)
1303                         return res;
1304         } else {
1305                 errno = ENOSYS;
1306                 return -1;
1307         }
1308         if (block) {
1309                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1310                    intermediate packets. XXX */
1311                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1312                 return -1;
1313         }
1314         return 0;
1315 }
1316