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