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