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