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