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