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