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