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