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