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