Version 0.1.8 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 struct ast_channel *ast_channel_alloc(void)
132 {
133         struct ast_channel *tmp;
134         struct ast_channel_pvt *pvt;
135         int x;
136         PTHREAD_MUTEX_LOCK(&chlock);
137         tmp = malloc(sizeof(struct ast_channel));
138         memset(tmp, 0, sizeof(struct ast_channel));
139         if (tmp) {
140                 pvt = malloc(sizeof(struct ast_channel_pvt));
141                 if (pvt) {
142                         memset(pvt, 0, sizeof(struct ast_channel_pvt));
143                         tmp->sched = sched_context_create();
144                         if (tmp->sched) {
145                                 for (x=0;x<AST_MAX_FDS;x++)
146                                         tmp->fds[x] = -1;
147                                 strncpy(tmp->name, "**Unknown**", sizeof(tmp->name));
148                                 tmp->pvt = pvt;
149                                 tmp->state = AST_STATE_DOWN;
150                                 tmp->stack = -1;
151                                 tmp->streamid = -1;
152                                 tmp->appl = NULL;
153                                 tmp->data = NULL;
154                                 pthread_mutex_init(&tmp->lock, NULL);
155                                 strncpy(tmp->context, "default", sizeof(tmp->context));
156                                 strncpy(tmp->language, defaultlanguage, sizeof(tmp->language));
157                                 strncpy(tmp->exten, "s", sizeof(tmp->exten));
158                                 tmp->priority=1;
159                                 tmp->next = channels;
160                                 channels= tmp;
161                         } else {
162                                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
163                                 free(tmp);
164                                 tmp = NULL;
165                         }
166                 } else {
167                         ast_log(LOG_WARNING, "Out of memory\n");
168                         free(tmp);
169                         tmp = NULL;
170                 }
171         } else 
172                 ast_log(LOG_WARNING, "Out of memory\n");
173         PTHREAD_MUTEX_UNLOCK(&chlock);
174         return tmp;
175 }
176
177 struct ast_channel *ast_channel_walk(struct ast_channel *prev)
178 {
179         struct ast_channel *l, *ret=NULL;
180         PTHREAD_MUTEX_LOCK(&chlock);
181         l = channels;
182         if (!prev) {
183                 PTHREAD_MUTEX_UNLOCK(&chlock);
184                 return l;
185         }
186         while(l) {
187                 if (l == prev)
188                         ret = l->next;
189                 l = l->next;
190         }
191         PTHREAD_MUTEX_UNLOCK(&chlock);
192         return ret;
193         
194 }
195
196 void ast_channel_free(struct ast_channel *chan)
197 {
198         struct ast_channel *last=NULL, *cur;
199         PTHREAD_MUTEX_LOCK(&chlock);
200         cur = channels;
201         while(cur) {
202                 if (cur == chan) {
203                         if (last)
204                                 last->next = cur->next;
205                         else
206                                 channels = cur->next;
207                         break;
208                 }
209                 last = cur;
210                 cur = cur->next;
211         }
212         if (!cur)
213                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
214         if (chan->pvt->pvt)
215                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
216         /* Free translatosr */
217         if (chan->pvt->readtrans)
218                 ast_translator_free_path(chan->pvt->readtrans);
219         if (chan->pvt->writetrans)
220                 ast_translator_free_path(chan->pvt->writetrans);
221         if (chan->pbx) 
222                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
223         if (chan->dnid)
224                 free(chan->dnid);
225         if (chan->callerid)
226                 free(chan->callerid);   
227         pthread_mutex_destroy(&chan->lock);
228         free(chan->pvt);
229         free(chan);
230         PTHREAD_MUTEX_UNLOCK(&chlock);
231 }
232
233 int ast_softhangup(struct ast_channel *chan)
234 {
235         int res = 0;
236         if (option_debug)
237                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
238         /* Inform channel driver that we need to be hung up, if it cares */
239         chan->softhangup = 1;           
240         /* Interrupt any select call or such */
241         if (chan->blocking)
242                 pthread_kill(chan->blocker, SIGURG);
243         return res;
244 }
245
246 int ast_hangup(struct ast_channel *chan)
247 {
248         int res = 0;
249         /* Don't actually hang up a channel that will masquerade as someone else, or
250            if someone is going to masquerade as us */
251         if (chan->masq)
252                 return 0;
253         /* If this channel is one which will be masqueraded into something, 
254            mark it as a zombie already, so we know to free it later */
255         if (chan->masqr) {
256                 chan->zombie=1;
257                 return 0;
258         }
259         if (chan->stream)
260                 ast_stopstream(chan);
261         if (chan->sched)
262                 sched_context_destroy(chan->sched);
263         if (chan->blocking) {
264                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
265                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
266                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
267                 CRASH;
268         }
269         if (!chan->zombie) {
270                 if (option_debug)
271                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
272                 if (chan->pvt->hangup)
273                         res = chan->pvt->hangup(chan);
274         } else
275                 if (option_debug)
276                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
277                         
278         ast_channel_free(chan);
279         return res;
280 }
281
282 void ast_channel_unregister(char *type)
283 {
284         struct chanlist *chan, *last=NULL;
285         if (option_debug)
286                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
287         if (PTHREAD_MUTEX_LOCK(&chlock)) {
288                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
289                 return;
290         }
291         chan = backends;
292         while(chan) {
293                 if (!strcasecmp(chan->type, type)) {
294                         if (last)
295                                 last->next = chan->next;
296                         else
297                                 backends = backends->next;
298                         free(chan);
299                         PTHREAD_MUTEX_UNLOCK(&chlock);
300                         return;
301                 }
302                 last = chan;
303                 chan = chan->next;
304         }
305         PTHREAD_MUTEX_UNLOCK(&chlock);
306 }
307
308 int ast_answer(struct ast_channel *chan)
309 {
310         /* Stop if we're a zombie or need a soft hangup */
311         if (chan->zombie || chan->softhangup) 
312                 return -1;
313         switch(chan->state) {
314         case AST_STATE_RING:
315         case AST_STATE_RINGING:
316                 if (chan->pvt->answer)
317                         return chan->pvt->answer(chan);
318                 chan->state = AST_STATE_UP;
319                 break;
320         case AST_STATE_UP:
321                 break;
322         }
323         return 0;
324 }
325
326 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
327 {
328         /* Wait for x amount of time on a file descriptor to have input.  */
329         struct timeval tv;
330         fd_set rfds, efds;
331         int res;
332         int x, max=-1;
333         int winner = -1;
334         
335         tv.tv_sec = *ms / 1000;
336         tv.tv_usec = (*ms % 1000) * 1000;
337         FD_ZERO(&rfds);
338         FD_ZERO(&efds);
339         for (x=0;x<n;x++) {
340                 if (fds[x] > -1) {
341                         FD_SET(fds[x], &rfds);
342                         FD_SET(fds[x], &efds);
343                         if (fds[x] > max)
344                                 max = fds[x];
345                 }
346         }
347         if (*ms >= 0) 
348                 res = select(max + 1, &rfds, NULL, &efds, &tv);
349         else
350                 res = select(max + 1, &rfds, NULL, &efds, NULL);
351
352         if (res < 0) {
353                 /* Simulate a timeout if we were interrupted */
354                 if (errno != EINTR)
355                         *ms = -1;
356                 else
357                         *ms = 0;
358                 return -1;
359         }
360
361         for (x=0;x<n;x++) {
362                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
363                         if (exception)
364                                 *exception = FD_ISSET(fds[x], &efds);
365                         winner = fds[x];
366                 }
367         }
368         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
369         return winner;
370 }
371
372 static int ast_do_masquerade(struct ast_channel *original);
373
374 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
375 {
376         /* Wait for x amount of time on a file descriptor to have input.  */
377         struct timeval tv;
378         fd_set rfds, efds;
379         int res;
380         int x, y, max=-1;
381         struct ast_channel *winner = NULL;
382         
383         /* Perform any pending masquerades */
384         for (x=0;x<n;x++) {
385                 if (c[x]->masq) {
386                         if (ast_do_masquerade(c[x])) {
387                                 ast_log(LOG_WARNING, "Masquerade failed\n");
388                                 *ms = -1;
389                                 return NULL;
390                         }
391                 }
392         }
393         
394         tv.tv_sec = *ms / 1000;
395         tv.tv_usec = (*ms % 1000) * 1000;
396         FD_ZERO(&rfds);
397         FD_ZERO(&efds);
398         for (x=0;x<n;x++) {
399                 for (y=0;y<AST_MAX_FDS;y++) {
400                         if (c[x]->fds[y] > 0) {
401                                 FD_SET(c[x]->fds[y], &rfds);
402                                 FD_SET(c[x]->fds[y], &efds);
403                                 if (c[x]->fds[y] > max)
404                                         max = c[x]->fds[y];
405                         }
406                 }
407                 CHECK_BLOCKING(c[x]);
408         }
409         if (*ms >= 0) 
410                 res = select(max + 1, &rfds, NULL, &efds, &tv);
411         else
412                 res = select(max + 1, &rfds, NULL, &efds, NULL);
413
414         if (res < 0) {
415                 for (x=0;x<n;x++) 
416                         c[x]->blocking = 0;
417                 /* Simulate a timeout if we were interrupted */
418                 if (errno != EINTR)
419                         *ms = -1;
420                 else
421                         *ms = 0;
422                 return NULL;
423         }
424
425         for (x=0;x<n;x++) {
426                 c[x]->blocking = 0;
427                 for (y=0;y<AST_MAX_FDS;y++) {
428                         if (c[x]->fds[y] > -1) {
429                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
430                                         /* Set exception flag if appropriate */
431                                         if (FD_ISSET(c[x]->fds[y], &efds))
432                                                 c[x]->exception = 1;
433                                         c[x]->fdno = y;
434                                         winner = c[x];
435                                 }
436                         }
437                 }
438         }
439         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
440         return winner;
441 }
442
443 int ast_waitfor(struct ast_channel *c, int ms)
444 {
445         struct ast_channel *chan;
446         chan = ast_waitfor_n(&c, 1, &ms);
447         if (ms < 0)
448                 return -1;
449         return ms;
450 }
451
452 char ast_waitfordigit(struct ast_channel *c, int ms)
453 {
454         struct ast_frame *f;
455         char result = 0;
456         /* Stop if we're a zombie or need a soft hangup */
457         if (c->zombie || c->softhangup) 
458                 return -1;
459         /* Wait for a digit, no more than ms milliseconds total. */
460         while(ms && !result) {
461                 ms = ast_waitfor(c, ms);
462                 if (ms < 0) /* Error */
463                         result = -1; 
464                 else if (ms > 0) {
465                         /* Read something */
466                         f = ast_read(c);
467                         if (f) {
468                                 if (f->frametype == AST_FRAME_DTMF) 
469                                         result = f->subclass;
470                                 ast_frfree(f);
471                         } else
472                                 result = -1;
473                 }
474         }
475         return result;
476 }
477
478 struct ast_frame *ast_read(struct ast_channel *chan)
479 {
480         struct ast_frame *f = NULL;
481         static struct ast_frame null_frame = 
482         {
483                 AST_FRAME_NULL,
484         };
485         
486         pthread_mutex_lock(&chan->lock);
487         if (chan->masq) {
488                 if (ast_do_masquerade(chan)) {
489                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
490                         f = NULL;
491                 } else
492                         f =  &null_frame;
493                 pthread_mutex_unlock(&chan->lock);
494                 return f;
495         }
496
497         /* Stop if we're a zombie or need a soft hangup */
498         if (chan->zombie || chan->softhangup) {
499                 pthread_mutex_unlock(&chan->lock);
500                 return NULL;
501         }
502                 
503         chan->blocker = pthread_self();
504         if (chan->exception) {
505                 if (chan->pvt->exception) 
506                         f = chan->pvt->exception(chan);
507                 else
508                         ast_log(LOG_WARNING, "Exception flag set, but no exception handler\n");
509                 /* Clear the exception flag */
510                 chan->exception = 0;
511         } else
512         if (chan->pvt->read)
513                 f = chan->pvt->read(chan);
514         else
515                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan);
516         if (f && (f->frametype == AST_FRAME_VOICE)) {
517                 if (chan->pvt->readtrans) {
518                         f = ast_translate(chan->pvt->readtrans, f, 1);
519                         if (!f)
520                                 f = &null_frame;
521                 }
522         }
523         /* Make sure we always return NULL in the future */
524         if (!f)
525                 chan->softhangup = 1;
526         pthread_mutex_unlock(&chan->lock);
527
528         return f;
529 }
530
531 int ast_indicate(struct ast_channel *chan, int condition)
532 {
533         int res = -1;
534         /* Stop if we're a zombie or need a soft hangup */
535         if (chan->zombie || chan->softhangup) 
536                 return -1;
537         if (chan->pvt->indicate) {
538                 res = chan->pvt->indicate(chan, condition);
539                 if (res)
540                         ast_log(LOG_WARNING, "Driver for channel '%s' failed to indicate condition %d\n", chan->name, condition);
541         } else
542                 ast_log(LOG_WARNING, "Driver for channel '%s' does not support indication\n", chan->name);
543         return res;
544 }
545
546 int ast_sendtext(struct ast_channel *chan, char *text)
547 {
548         int res = 0;
549         /* Stop if we're a zombie or need a soft hangup */
550         if (chan->zombie || chan->softhangup) 
551                 return -1;
552         CHECK_BLOCKING(chan);
553         if (chan->pvt->send_text)
554                 res = chan->pvt->send_text(chan, text);
555         chan->blocking = 0;
556         return res;
557 }
558
559 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
560 {
561         int res = -1;
562         struct ast_frame *f;
563         /* Stop if we're a zombie or need a soft hangup */
564         if (chan->zombie || chan->softhangup) 
565                 return -1;
566         /* Handle any pending masquerades */
567         if (chan->masq) {
568                 if (ast_do_masquerade(chan)) {
569                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
570                         return -1;
571                 }
572         }
573         if (chan->masqr)
574                 return 0;
575         CHECK_BLOCKING(chan);
576         switch(fr->frametype) {
577         case AST_FRAME_CONTROL:
578                 /* XXX Interpret control frames XXX */
579                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
580                 break;
581         case AST_FRAME_DTMF:
582                 
583                 if (chan->pvt->send_digit)
584                         res = chan->pvt->send_digit(chan, fr->subclass);
585                 break;
586         default:
587                 if (chan->pvt->write) {
588                         if (chan->pvt->writetrans) {
589                                 f = ast_translate(chan->pvt->writetrans, fr, 1);
590                         } else
591                                 f = fr;
592                         if (f)  
593                                 res = chan->pvt->write(chan, f);
594                         else
595                                 res = 0;
596                 }
597         }
598         chan->blocking = 0;
599         return res;
600 }
601
602 int ast_set_write_format(struct ast_channel *chan, int fmts)
603 {
604         int fmt;
605         int native;
606         int res;
607         
608         native = chan->nativeformats;
609         fmt = fmts;
610         
611         res = ast_translator_best_choice(&native, &fmt);
612         if (res < 0) {
613                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
614                 return -1;
615         }
616         
617         /* Now we have a good choice for both.  We'll write using our native format. */
618         chan->pvt->rawwriteformat = native;
619         /* User perspective is fmt */
620         chan->writeformat = fmt;
621         /* Free any write translation we have right now */
622         if (chan->pvt->writetrans)
623                 ast_translator_free_path(chan->pvt->writetrans);
624         /* Build a translation path from the user write format to the raw writing format */
625         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
626         if (option_debug)
627                 ast_log(LOG_DEBUG, "Set channel %s to format %d\n", chan->name, chan->writeformat);
628         return 0;
629 }
630
631 int ast_set_read_format(struct ast_channel *chan, int fmts)
632 {
633         int fmt;
634         int native;
635         int res;
636         
637         native = chan->nativeformats;
638         fmt = fmts;
639         /* Find a translation path from the native read format to one of the user's read formats */
640         res = ast_translator_best_choice(&fmt, &native);
641         if (res < 0) {
642                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
643                 return -1;
644         }
645         
646         /* Now we have a good choice for both.  We'll write using our native format. */
647         chan->pvt->rawreadformat = native;
648         /* User perspective is fmt */
649         chan->readformat = fmt;
650         /* Free any read translation we have right now */
651         if (chan->pvt->readtrans)
652                 ast_translator_free_path(chan->pvt->readtrans);
653         /* Build a translation path from the raw read format to the user reading format */
654         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
655         return 0;
656 }
657
658 struct ast_channel *ast_request(char *type, int format, void *data)
659 {
660         struct chanlist *chan;
661         struct ast_channel *c = NULL;
662         int capabilities;
663         int fmt;
664         int res;
665         if (PTHREAD_MUTEX_LOCK(&chlock)) {
666                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
667                 return NULL;
668         }
669         chan = backends;
670         while(chan) {
671                 if (!strcasecmp(type, chan->type)) {
672                         capabilities = chan->capabilities;
673                         fmt = format;
674                         res = ast_translator_best_choice(&fmt, &capabilities);
675                         if (res < 0) {
676                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
677                                 PTHREAD_MUTEX_UNLOCK(&chlock);
678                                 return NULL;
679                         }
680                         PTHREAD_MUTEX_UNLOCK(&chlock);
681                         if (chan->requester)
682                                 c = chan->requester(type, capabilities, data);
683                         return c;
684                 }
685                 chan = chan->next;
686         }
687         if (!chan)
688                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
689         PTHREAD_MUTEX_UNLOCK(&chlock);
690         return c;
691 }
692
693 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
694 {
695         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
696            If the remote end does not answer within the timeout, then do NOT hang up, but 
697            return anyway.  */
698         int res = -1;
699         /* Stop if we're a zombie or need a soft hangup */
700         pthread_mutex_lock(&chan->lock);
701         if (!chan->zombie && !chan->softhangup) 
702                 if (chan->pvt->call)
703                         res = chan->pvt->call(chan, addr, timeout);
704         pthread_mutex_unlock(&chan->lock);
705         return res;
706 }
707
708 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
709 {
710         int pos=0;
711         int to = ftimeout;
712         char d;
713         /* Stop if we're a zombie or need a soft hangup */
714         if (c->zombie || c->softhangup) 
715                 return -1;
716         if (!len)
717                 return -1;
718         do {
719                 if (c->streamid > -1) {
720                         d = ast_waitstream(c, AST_DIGIT_ANY);
721                         ast_stopstream(c);
722                         usleep(1000);
723                         if (!d)
724                                 d = ast_waitfordigit(c, to);
725                 } else {
726                         d = ast_waitfordigit(c, to);
727                 }
728                 if (d < 0)
729                         return -1;
730                 if (!strchr(enders, d))
731                         s[pos++] = d;
732                 if ((d == 0) || strchr(enders, d) || (pos >= len - 1)) {
733                         s[pos]='\0';
734                         return 0;
735                 }
736                 to = timeout;
737         } while(1);
738         /* Never reached */
739         return 0;
740 }
741
742 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
743 {
744         int peerf;
745         int chanf;
746         int res;
747         peerf = peer->nativeformats;
748         chanf = chan->nativeformats;
749         res = ast_translator_best_choice(&peerf, &chanf);
750         if (res < 0) {
751                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan, chan->nativeformats, peer, peer->nativeformats);
752                 return -1;
753         }
754         /* Set read format on channel */
755         res = ast_set_read_format(chan, peerf);
756         if (res < 0) {
757                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan, chanf);
758                 return -1;
759         }
760         /* Set write format on peer channel */
761         res = ast_set_write_format(peer, peerf);
762         if (res < 0) {
763                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer, peerf);
764                 return -1;
765         }
766         /* Now we go the other way */
767         peerf = peer->nativeformats;
768         chanf = chan->nativeformats;
769         res = ast_translator_best_choice(&chanf, &peerf);
770         if (res < 0) {
771                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer, peer->nativeformats, chan, chan->nativeformats);
772                 return -1;
773         }
774         /* Set writeformat on channel */
775         res = ast_set_write_format(chan, chanf);
776         if (res < 0) {
777                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan, chanf);
778                 return -1;
779         }
780         /* Set read format on peer channel */
781         res = ast_set_read_format(peer, chanf);
782         if (res < 0) {
783                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer, peerf);
784                 return -1;
785         }
786         return 0;
787 }
788
789 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
790 {
791         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
792                 clone->name, original->name);
793         if (original->masq) {
794                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
795                         original->masq->name, original->name);
796                 return -1;
797         }
798         if (clone->masqr) {
799                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
800                         clone->name, clone->masqr->name);
801                 return -1;
802         }
803         original->masq = clone;
804         clone->masqr = original;
805         return 0;
806 }
807
808 static int ast_do_masquerade(struct ast_channel *original)
809 {
810         int x;
811         int res=0;
812         char *tmp;
813         struct ast_channel_pvt *p;
814         struct ast_channel *clone = original->masq;
815         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
816                 clone->name, clone->state, original->name, original->state);
817         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
818            the clone channel into the original channel.  Start by killing off the original
819            channel's backend.   I'm not sure we're going to keep this function, because 
820            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
821
822         /* We need the clone's lock, too */
823         pthread_mutex_lock(&clone->lock);
824
825         /* Unlink the masquerade */
826         original->masq = NULL;
827         clone->masqr = NULL;
828                 
829         /* Copy the name from the clone channel */
830         strncpy(original->name, clone->name, sizeof(original->name));
831
832         /* Mangle the name of the clone channel */
833         strncat(clone->name, "<MASQ>", sizeof(clone->name));
834
835         /* Swap the guts */     
836         p = original->pvt;
837         original->pvt = clone->pvt;
838         clone->pvt = p;
839
840         /* Start by disconnecting the original's physical side */
841         if (clone->pvt->hangup)
842                 res = clone->pvt->hangup(clone);
843         if (res) {
844                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
845                 pthread_mutex_unlock(&clone->lock);
846                 return -1;
847         }
848         
849         /* Mangle the name of the clone channel */
850         snprintf(clone->name, sizeof(clone->name), "%s<ZOMBIE>", original->name);
851
852         /* Keep the same language.  */
853         /* Update the type. */
854         original->type = clone->type;
855         /* Copy the FD's */
856         for (x=0;x<AST_MAX_FDS;x++)
857                 original->fds[x] = clone->fds[x];
858         /* Bridge remains the same */
859         /* CDR fields remain the same */
860         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
861         /* Application and data remain the same */
862         /* Clone exception  becomes real one, as with fdno */
863         original->exception = clone->exception;
864         original->fdno = clone->fdno;
865         /* Schedule context remains the same */
866         /* Stream stuff stays the same */
867         /* Keep the original state.  The fixup code will need to work with it most likely */
868
869         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
870            fields back into the defunct 'clone' so that they will be freed when
871            ast_frfree is eventually called */
872         tmp = original->dnid;
873         original->dnid = clone->dnid;
874         clone->dnid = tmp;
875         
876         tmp = original->callerid;
877         original->callerid = clone->callerid;
878         clone->callerid = tmp;
879         
880         /* Context, extension, priority, app data, jump table,  remain the same */
881         /* pvt switches.  pbx stays the same, as does next */
882         
883         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
884            a zombie so nothing tries to touch it.  If it's already been marked as a
885            zombie, then free it now (since it already is considered invalid). */
886         if (clone->zombie) {
887                 pthread_mutex_unlock(&clone->lock);
888                 ast_channel_free(clone);
889         } else {
890                 clone->zombie=1;
891                 pthread_mutex_unlock(&clone->lock);
892         }
893         /* Set the write format */
894         ast_set_write_format(original, original->writeformat);
895
896         /* Set the read format */
897         ast_set_read_format(original, original->readformat);
898
899         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
900            can fix up everything as best as possible */
901         if (original->pvt->fixup) {
902                 res = original->pvt->fixup(clone, original);
903                 if (res) {
904                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
905                                 original->type, original->name);
906                         return -1;
907                 }
908         } else
909                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
910                         original->type, original->name);
911         
912         /* Signal any blocker */
913         if (original->blocking)
914                 pthread_kill(original->blocker, SIGURG);
915         return 0;
916 }
917
918 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
919 {
920         /* Copy voice back and forth between the two channels.  Give the peer
921            the ability to transfer calls with '#<extension' syntax. */
922         struct ast_channel *cs[3];
923         int to = -1;
924         struct ast_frame *f;
925         struct ast_channel *who;
926         int res;
927         /* Stop if we're a zombie or need a soft hangup */
928         if (c0->zombie || c0->softhangup || c1->zombie || c1->softhangup) 
929                 return -1;
930         if (c0->bridge) {
931                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
932                         c0->name, c0->bridge->name);
933                 return -1;
934         }
935         if (c1->bridge) {
936                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
937                         c1->name, c1->bridge->name);
938                 return -1;
939         }
940         
941         /* Keep track of bridge */
942         c0->bridge = c1;
943         c1->bridge = c0;
944         
945         if (c0->pvt->bridge && 
946                 (c0->pvt->bridge == c1->pvt->bridge)) {
947                         /* Looks like they share a bridge code */
948                 if (!c0->pvt->bridge(c0, c1, flags, fo, rc)) {
949                         c0->bridge = NULL;
950                         c1->bridge = NULL;
951                         return 0;
952                 }
953                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
954                 /* If they return non-zero then continue on normally */
955         }
956         
957         
958         
959         cs[0] = c0;
960         cs[1] = c1;
961         for (/* ever */;;) {
962                 who = ast_waitfor_n(cs, 2, &to);
963                 if (!who) {
964                         ast_log(LOG_WARNING, "Nobody there??\n"); 
965                         continue;
966                 }
967                 f = ast_read(who);
968                 if (!f) {
969                         *fo = NULL;
970                         *rc = who;
971                         res = 0;
972                         break;
973                 }
974                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
975                         *fo = f;
976                         *rc = who;
977                         res =  0;
978                         break;
979                 }
980                 if ((f->frametype == AST_FRAME_VOICE) ||
981                         (f->frametype == AST_FRAME_TEXT) ||
982                         (f->frametype == AST_FRAME_VIDEO) || 
983                         (f->frametype == AST_FRAME_IMAGE) ||
984                         (f->frametype == AST_FRAME_DTMF)) {
985                         if ((f->frametype == AST_FRAME_DTMF) && 
986                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
987                                 if ((who == c0)) {
988                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
989                                                 *rc = c0;
990                                                 *fo = f;
991                                                 /* Take out of conference mode */
992                                                 res = 0;
993                                                 break;
994                                         } else 
995                                                 goto tackygoto;
996                                 } else
997                                 if ((who == c1)) {
998                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
999                                                 *rc = c1;
1000                                                 *fo = f;
1001                                                 res =  0;
1002                                                 break;
1003                                         } else
1004                                                 goto tackygoto;
1005                                 }
1006                         } else {
1007 #if 0
1008                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
1009                                 if (who == last) 
1010                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
1011                                 last = who;
1012 #endif
1013 tackygoto:
1014                                 if (who == c0) 
1015                                         ast_write(c1, f);
1016                                 else 
1017                                         ast_write(c0, f);
1018                         }
1019                         ast_frfree(f);
1020                 } else
1021                         ast_frfree(f);
1022                 /* Swap who gets priority */
1023                 cs[2] = cs[0];
1024                 cs[0] = cs[1];
1025                 cs[1] = cs[2];
1026         }
1027         c0->bridge = NULL;
1028         c1->bridge = NULL;
1029         return res;
1030 }
1031
1032 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
1033 {
1034         int res;
1035         if (chan->pvt->setoption) {
1036                 res = chan->pvt->setoption(chan, option, data, datalen);
1037                 if (res < 0)
1038                         return res;
1039         } else {
1040                 errno = ENOSYS;
1041                 return -1;
1042         }
1043         if (block) {
1044                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
1045                    intermediate packets. XXX */
1046                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
1047                 return -1;
1048         }
1049         return 0;
1050 }