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