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