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