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