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