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