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