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