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