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