Revert Jim's earlier "fix" :)
[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         ast_mutex_lock(&original->lock);
2212         while(ast_mutex_trylock(&clone->lock)) {
2213                 ast_mutex_unlock(&original->lock);
2214                 usleep(1);
2215                 ast_mutex_lock(&original->lock);
2216         }
2217         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2218                 clone->name, original->name);
2219         if (original->masq) {
2220                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2221                         original->masq->name, original->name);
2222         } else if (clone->masqr) {
2223                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2224                         clone->name, clone->masqr->name);
2225         } else {
2226                 original->masq = clone;
2227                 clone->masqr = original;
2228                 ast_queue_frame(original, &null);
2229                 ast_queue_frame(clone, &null);
2230                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2231                 res = 0;
2232         }
2233         ast_mutex_unlock(&clone->lock);
2234         ast_mutex_unlock(&original->lock);
2235         return res;
2236 }
2237
2238 void ast_change_name(struct ast_channel *chan, char *newname)
2239 {
2240         char tmp[256];
2241         strncpy(tmp, chan->name, sizeof(tmp) - 1);
2242         strncpy(chan->name, newname, sizeof(chan->name) - 1);
2243         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2244 }
2245
2246 /* Clone channel variables from 'clone' channel into 'original' channel
2247    All variables except those related to app_groupcount are cloned
2248    Variables are actually _removed_ from 'clone' channel, presumably
2249    because it will subsequently be destroyed.
2250    Assumes locks will be in place on both channels when called.
2251 */
2252    
2253 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2254 {
2255         struct ast_var_t *varptr;
2256
2257         /* we need to remove all app_groupcount related variables from the original
2258            channel before merging in the clone's variables; any groups assigned to the
2259            original channel should be released, only those assigned to the clone
2260            should remain
2261         */
2262
2263         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2264                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2265                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2266                         ast_var_delete(varptr);
2267                 }
2268         }
2269         AST_LIST_TRAVERSE_SAFE_END;
2270
2271         /* Append variables from clone channel into original channel */
2272         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2273         AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2274 }
2275
2276 /* Assumes channel will be locked when called */
2277 int ast_do_masquerade(struct ast_channel *original)
2278 {
2279         int x,i;
2280         int res=0;
2281         int origstate;
2282         struct ast_frame *cur, *prev;
2283         struct ast_channel_pvt *p;
2284         struct ast_callerid tmpcid;
2285         struct ast_channel *clone = original->masq;
2286         int rformat = original->readformat;
2287         int wformat = original->writeformat;
2288         char newn[100];
2289         char orig[100];
2290         char masqn[100];
2291         char zombn[100];
2292         
2293 #if 1
2294         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2295                 clone->name, clone->_state, original->name, original->_state);
2296 #endif
2297         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2298            the clone channel into the original channel.  Start by killing off the original
2299            channel's backend.   I'm not sure we're going to keep this function, because 
2300            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2301
2302         /* We need the clone's lock, too */
2303         ast_mutex_lock(&clone->lock);
2304
2305         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2306
2307         /* Having remembered the original read/write formats, we turn off any translation on either
2308            one */
2309         free_translation(clone);
2310         free_translation(original);
2311
2312
2313         /* Unlink the masquerade */
2314         original->masq = NULL;
2315         clone->masqr = NULL;
2316         
2317         /* Save the original name */
2318         strncpy(orig, original->name, sizeof(orig) - 1);
2319         /* Save the new name */
2320         strncpy(newn, clone->name, sizeof(newn) - 1);
2321         /* Create the masq name */
2322         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2323                 
2324         /* Copy the name from the clone channel */
2325         strncpy(original->name, newn, sizeof(original->name)-1);
2326
2327         /* Mangle the name of the clone channel */
2328         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2329         
2330         /* Notify any managers of the change, first the masq then the other */
2331         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2332         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2333
2334         /* Swap the guts */     
2335         p = original->pvt;
2336         original->pvt = clone->pvt;
2337         clone->pvt = p;
2338
2339         /* Save any pending frames on both sides.  Start by counting
2340          * how many we're going to need... */
2341         prev = NULL;
2342         cur = clone->pvt->readq;
2343         x = 0;
2344         while(cur) {
2345                 x++;
2346                 prev = cur;
2347                 cur = cur->next;
2348         }
2349         /* If we had any, prepend them to the ones already in the queue, and 
2350          * load up the alertpipe */
2351         if (prev) {
2352                 prev->next = original->pvt->readq;
2353                 original->pvt->readq = clone->pvt->readq;
2354                 clone->pvt->readq = NULL;
2355                 if (original->pvt->alertpipe[1] > -1) {
2356                         for (i=0;i<x;i++)
2357                                 write(original->pvt->alertpipe[1], &x, sizeof(x));
2358                 }
2359         }
2360         clone->_softhangup = AST_SOFTHANGUP_DEV;
2361
2362
2363         /* And of course, so does our current state.  Note we need not
2364            call ast_setstate since the event manager doesn't really consider
2365            these separate.  We do this early so that the clone has the proper
2366            state of the original channel. */
2367         origstate = original->_state;
2368         original->_state = clone->_state;
2369         clone->_state = origstate;
2370
2371         if (clone->pvt->fixup){
2372                 res = clone->pvt->fixup(original, clone);
2373                 if (res) 
2374                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2375         }
2376
2377         /* Start by disconnecting the original's physical side */
2378         if (clone->pvt->hangup)
2379                 res = clone->pvt->hangup(clone);
2380         if (res) {
2381                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2382                 ast_mutex_unlock(&clone->lock);
2383                 return -1;
2384         }
2385         
2386         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2387         /* Mangle the name of the clone channel */
2388         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2389         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2390
2391         /* Keep the same language.  */
2392         /* Update the type. */
2393         original->type = clone->type;
2394         /* Copy the FD's */
2395         for (x=0;x<AST_MAX_FDS;x++) {
2396                 original->fds[x] = clone->fds[x];
2397         }
2398         clone_variables(original, clone);
2399         clone->varshead.first = NULL;
2400         /* Presense of ADSI capable CPE follows clone */
2401         original->adsicpe = clone->adsicpe;
2402         /* Bridge remains the same */
2403         /* CDR fields remain the same */
2404         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2405         /* Application and data remain the same */
2406         /* Clone exception  becomes real one, as with fdno */
2407         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2408         original->fdno = clone->fdno;
2409         /* Schedule context remains the same */
2410         /* Stream stuff stays the same */
2411         /* Keep the original state.  The fixup code will need to work with it most likely */
2412
2413         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2414            out. */
2415         tmpcid = original->cid;
2416         original->cid = clone->cid;
2417         clone->cid = tmpcid;
2418         
2419         /* Restore original timing file descriptor */
2420         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2421         
2422         /* Our native formats are different now */
2423         original->nativeformats = clone->nativeformats;
2424         
2425         /* Context, extension, priority, app data, jump table,  remain the same */
2426         /* pvt switches.  pbx stays the same, as does next */
2427         
2428         /* Set the write format */
2429         ast_set_write_format(original, wformat);
2430
2431         /* Set the read format */
2432         ast_set_read_format(original, rformat);
2433
2434         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2435
2436         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2437            can fix up everything as best as possible */
2438         if (original->pvt->fixup) {
2439                 res = original->pvt->fixup(clone, original);
2440                 if (res) {
2441                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2442                                 original->type, original->name);
2443                         ast_mutex_unlock(&clone->lock);
2444                         return -1;
2445                 }
2446         } else
2447                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2448                         original->type, original->name);
2449         
2450         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2451            a zombie so nothing tries to touch it.  If it's already been marked as a
2452            zombie, then free it now (since it already is considered invalid). */
2453         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2454                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2455                 ast_mutex_unlock(&clone->lock);
2456                 ast_channel_free(clone);
2457                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2458         } else {
2459                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2460                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2461                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2462                 ast_queue_frame(clone, &null_frame);
2463                 ast_mutex_unlock(&clone->lock);
2464         }
2465         
2466         /* Signal any blocker */
2467         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2468                 pthread_kill(original->blocker, SIGURG);
2469         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2470                 original->name, original->_state);
2471         return 0;
2472 }
2473
2474 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2475 {
2476         if (callerid) {
2477                 if (chan->cid.cid_num)
2478                         free(chan->cid.cid_num);
2479                 if (ast_strlen_zero(callerid))
2480                         chan->cid.cid_num = NULL;
2481                 else
2482                         chan->cid.cid_num = strdup(callerid);
2483         }
2484         if (calleridname) {
2485                 if (chan->cid.cid_name)
2486                         free(chan->cid.cid_name);
2487                 if (ast_strlen_zero(calleridname))
2488                         chan->cid.cid_name = NULL;
2489                 else
2490                         chan->cid.cid_name = strdup(calleridname);
2491         }
2492         if (ani) {
2493                 if (chan->cid.cid_ani)
2494                         free(chan->cid.cid_ani);
2495                 if (ast_strlen_zero(ani))
2496                         chan->cid.cid_ani = NULL;
2497                 else
2498                         chan->cid.cid_ani = strdup(ani);
2499         }
2500         if (chan->cdr)
2501                 ast_cdr_setcid(chan->cdr, chan);
2502         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2503                                 "Channel: %s\r\n"
2504                                 "CallerID: %s\r\n"
2505                                 "CallerIDName: %s\r\n"
2506                                 "Uniqueid: %s\r\n",
2507                                 chan->name, chan->cid.cid_num ? 
2508                                 chan->cid.cid_num : "<Unknown>",
2509                                 chan->cid.cid_name ? 
2510                                 chan->cid.cid_name : "<Unknown>",
2511                                 chan->uniqueid);
2512 }
2513
2514 int ast_setstate(struct ast_channel *chan, int state)
2515 {
2516         if (chan->_state != state) {
2517                 int oldstate = chan->_state;
2518                 chan->_state = state;
2519                 if (oldstate == AST_STATE_DOWN) {
2520                         ast_device_state_changed(chan->name);
2521                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2522                         "Channel: %s\r\n"
2523                         "State: %s\r\n"
2524                         "CallerID: %s\r\n"
2525                         "CallerIDName: %s\r\n"
2526                         "Uniqueid: %s\r\n",
2527                         chan->name, ast_state2str(chan->_state), 
2528                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2529                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2530                         chan->uniqueid);
2531                 } else {
2532                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2533                                 "Channel: %s\r\n"
2534                                 "State: %s\r\n"
2535                                 "CallerID: %s\r\n"
2536                                 "CallerIDName: %s\r\n"
2537                                 "Uniqueid: %s\r\n",
2538                                 chan->name, ast_state2str(chan->_state), 
2539                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2540                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2541                                 chan->uniqueid);
2542                 }
2543         }
2544         return 0;
2545 }
2546
2547 static long tvdiff(struct timeval *now, struct timeval *then) 
2548 {
2549         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2550 }
2551
2552 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2553 {
2554         struct ast_channel *bridged;
2555         bridged = chan->_bridge;
2556         if (bridged && bridged->pvt->bridged_channel) 
2557                 bridged = bridged->pvt->bridged_channel(chan, bridged);
2558         return bridged;
2559 }
2560
2561 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2562 {
2563         int res=0, min=0, sec=0,check=0;
2564
2565         check = ast_autoservice_start(peer);
2566         if(check) 
2567                 return;
2568
2569         if (remain > 0) {
2570                 if (remain / 60 > 1) {
2571                         min = remain / 60;
2572                         sec = remain % 60;
2573                 } else {
2574                         sec = remain;
2575                 }
2576         }
2577         
2578         if (!strcmp(sound,"timeleft")) {
2579                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2580                 res = ast_waitstream(chan, "");
2581                 if (min) {
2582                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2583                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2584                         res = ast_waitstream(chan, "");
2585                 }
2586                 if (sec) {
2587                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2588                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2589                         res = ast_waitstream(chan, "");
2590                 }
2591         } else {
2592                 res = ast_streamfile(chan, sound, chan->language);
2593                 res = ast_waitstream(chan, "");
2594         }
2595
2596         check = ast_autoservice_stop(peer);
2597 }
2598
2599 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) 
2600 {
2601         /* Copy voice back and forth between the two channels.  Give the peer
2602            the ability to transfer calls with '#<extension' syntax. */
2603         struct ast_channel *cs[3];
2604         int to = -1;
2605         struct ast_frame *f;
2606         struct ast_channel *who = NULL;
2607         int res=0;
2608         int nativefailed=0;
2609         int firstpass;
2610         int o0nativeformats;
2611         int o1nativeformats;
2612         struct timeval start_time,precise_now;
2613         long elapsed_ms=0, time_left_ms=0;
2614         int playit=0, playitagain=1, first_time=1;
2615
2616         *fo = NULL;
2617         firstpass = config->firstpass;
2618         config->firstpass = 0;
2619
2620         /* timestamp */
2621         gettimeofday(&start_time,NULL);
2622         time_left_ms = config->timelimit;
2623
2624         if ((config->features_caller & AST_FEATURE_PLAY_WARNING) && config->start_sound && firstpass)
2625                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2626         if ((config->features_callee & AST_FEATURE_PLAY_WARNING) && config->start_sound && firstpass)
2627                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2628
2629         /* Stop if we're a zombie or need a soft hangup */
2630         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)) 
2631                 return -1;
2632         if (c0->_bridge) {
2633                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2634                         c0->name, c0->_bridge->name);
2635                 return -1;
2636         }
2637         if (c1->_bridge) {
2638                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2639                         c1->name, c1->_bridge->name);
2640                 return -1;
2641         }
2642         
2643         /* Keep track of bridge */
2644         c0->_bridge = c1;
2645         c1->_bridge = c0;
2646         cs[0] = c0;
2647         cs[1] = c1;
2648         
2649         manager_event(EVENT_FLAG_CALL, "Link", 
2650                         "Channel1: %s\r\n"
2651                         "Channel2: %s\r\n"
2652                         "Uniqueid1: %s\r\n"
2653                         "Uniqueid2: %s\r\n",
2654                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2655         o1nativeformats = c1->nativeformats;
2656         o0nativeformats = c0->nativeformats;
2657         for (/* ever */;;) {
2658                 /* timestamp */
2659                 if (config->timelimit) {
2660                         gettimeofday(&precise_now,NULL);
2661                         elapsed_ms = tvdiff(&precise_now,&start_time);
2662                         time_left_ms = config->timelimit - elapsed_ms;
2663
2664                         if (playitagain && ((config->features_caller & AST_FEATURE_PLAY_WARNING) || (config->features_callee & AST_FEATURE_PLAY_WARNING)) && (config->play_warning && time_left_ms <= config->play_warning)) { 
2665                                 /* narrowing down to the end */
2666                                 if (config->warning_freq == 0) {
2667                                         playit = 1;
2668                                         first_time=0;
2669                                         playitagain=0;
2670                                 } else if (first_time) {
2671                                         playit = 1;
2672                                         first_time=0;
2673                                 } else {
2674                                         if ((time_left_ms % config->warning_freq) <= 50) {
2675                                                 playit = 1;
2676                                         }
2677                                 }
2678                         }
2679                         if (time_left_ms <= 0) {
2680                                 if ((config->features_caller & AST_FEATURE_PLAY_WARNING) && config->end_sound)
2681                                         bridge_playfile(c0,c1,config->end_sound,0);
2682                                 if ((config->features_callee & AST_FEATURE_PLAY_WARNING) && config->end_sound)
2683                                         bridge_playfile(c1,c0,config->end_sound,0);
2684                                 *fo = NULL;
2685                                 if (who) *rc = who;
2686                                 res = 0;
2687                                 break;
2688                         }
2689                         if (time_left_ms >= 5000 && playit) {
2690                                 if ((config->features_caller & AST_FEATURE_PLAY_WARNING) && config->warning_sound && config->play_warning)
2691                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2692                                 if ((config->features_callee & AST_FEATURE_PLAY_WARNING) && config->warning_sound && config->play_warning)
2693                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2694                                 playit = 0;
2695                         }
2696                         
2697                 }
2698                 /* Stop if we're a zombie or need a soft hangup */
2699                 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)) {
2700                         *fo = NULL;
2701                         if (who) *rc = who;
2702                         res = 0;
2703                         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");
2704                         break;
2705                 }
2706                 if (c0->pvt->bridge && config->timelimit==0 &&
2707                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2708                                 /* Looks like they share a bridge code */
2709                         if (option_verbose > 2) 
2710                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2711                         if (!(res = c0->pvt->bridge(c0, c1, config->flags, fo, rc))) {
2712                                 c0->_bridge = NULL;
2713                                 c1->_bridge = NULL;
2714                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2715                                         "Channel1: %s\r\n"
2716                                         "Channel2: %s\r\n"
2717                                         "Uniqueid1: %s\r\n"
2718                                         "Uniqueid2: %s\r\n",
2719                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2720                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2721                                 return 0;
2722                         }
2723                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2724                            my not wanting to bridge */
2725                         if ((res != -2) && (res != -3))
2726                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2727                         if (res != -3) nativefailed++;
2728                 }
2729         
2730                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2731                         !(c0->generator || c1->generator))  {
2732                         if (ast_channel_make_compatible(c0, c1)) {
2733                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2734                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2735                                         "Channel1: %s\r\n"
2736                                         "Channel2: %s\r\n"
2737                                         "Uniqueid1: %s\r\n"
2738                                         "Uniqueid2: %s\r\n",
2739                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2740                                 return -1;
2741                         }
2742                         o0nativeformats = c0->nativeformats;
2743                         o1nativeformats = c1->nativeformats;
2744                 }
2745                 who = ast_waitfor_n(cs, 2, &to);
2746                 if (!who) {
2747                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2748                         continue;
2749                 }
2750                 f = ast_read(who);
2751                 if (!f) {
2752                         *fo = NULL;
2753                         *rc = who;
2754                         res = 0;
2755                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2756                         break;
2757                 }
2758
2759                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2760                         *fo = f;
2761                         *rc = who;
2762                         res =  0;
2763                         ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2764                         break;
2765                 }
2766                 if ((f->frametype == AST_FRAME_VOICE) ||
2767                         (f->frametype == AST_FRAME_TEXT) ||
2768                         (f->frametype == AST_FRAME_VIDEO) || 
2769                         (f->frametype == AST_FRAME_IMAGE) ||
2770                         (f->frametype == AST_FRAME_DTMF)) {
2771                         if ((f->frametype == AST_FRAME_DTMF) && 
2772                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2773                                 if ((who == c0)) {
2774                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2775                                                 *rc = c0;
2776                                                 *fo = f;
2777                                                 /* Take out of conference mode */
2778                                                 res = 0;
2779                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2780                                                 break;
2781                                         } else 
2782                                                 goto tackygoto;
2783                                 } else
2784                                 if ((who == c1)) {
2785                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2786                                                 *rc = c1;
2787                                                 *fo = f;
2788                                                 res =  0;
2789                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2790                                                 break;
2791                                         } else
2792                                                 goto tackygoto;
2793                                 }
2794                         } else {
2795 #if 0
2796                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2797                                 if (who == last) 
2798                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2799                                 last = who;
2800 #endif
2801 tackygoto:
2802                                 /* Don't copy packets if there is a generator on either one, since they're
2803                                    not supposed to be listening anyway */
2804                                 if (who == c0) 
2805                                         ast_write(c1, f);
2806                                 else 
2807                                         ast_write(c0, f);
2808                         }
2809                         ast_frfree(f);
2810                 } else
2811                         ast_frfree(f);
2812                 /* Swap who gets priority */
2813                 cs[2] = cs[0];
2814                 cs[0] = cs[1];
2815                 cs[1] = cs[2];
2816         }
2817         c0->_bridge = NULL;
2818         c1->_bridge = NULL;
2819         manager_event(EVENT_FLAG_CALL, "Unlink", 
2820                                         "Channel1: %s\r\n"
2821                                         "Channel2: %s\r\n"
2822                                         "Uniqueid1: %s\r\n"
2823                                         "Uniqueid2: %s\r\n",
2824                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2825         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2826         return res;
2827 }
2828
2829 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2830 {
2831         int res;
2832         if (chan->pvt->setoption) {
2833                 res = chan->pvt->setoption(chan, option, data, datalen);
2834                 if (res < 0)
2835                         return res;
2836         } else {
2837                 errno = ENOSYS;
2838                 return -1;
2839         }
2840         if (block) {
2841                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2842                    intermediate packets. XXX */
2843                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2844                 return -1;
2845         }
2846         return 0;
2847 }
2848
2849 struct tonepair_def {
2850         int freq1;
2851         int freq2;
2852         int duration;
2853         int vol;
2854 };
2855
2856 struct tonepair_state {
2857         float freq1;
2858         float freq2;
2859         float vol;
2860         int duration;
2861         int pos;
2862         int origwfmt;
2863         struct ast_frame f;
2864         unsigned char offset[AST_FRIENDLY_OFFSET];
2865         short data[4000];
2866 };
2867
2868 static void tonepair_release(struct ast_channel *chan, void *params)
2869 {
2870         struct tonepair_state *ts = params;
2871         if (chan) {
2872                 ast_set_write_format(chan, ts->origwfmt);
2873         }
2874         free(ts);
2875 }
2876
2877 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2878 {
2879         struct tonepair_state *ts;
2880         struct tonepair_def *td = params;
2881         ts = malloc(sizeof(struct tonepair_state));
2882         if (!ts)
2883                 return NULL;
2884         memset(ts, 0, sizeof(struct tonepair_state));
2885         ts->origwfmt = chan->writeformat;
2886         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2887                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2888                 tonepair_release(NULL, ts);
2889                 ts = NULL;
2890         } else {
2891                 ts->freq1 = td->freq1;
2892                 ts->freq2 = td->freq2;
2893                 ts->duration = td->duration;
2894                 ts->vol = td->vol;
2895         }
2896         /* Let interrupts interrupt :) */
2897         ast_set_flag(chan, AST_FLAG_WRITE_INT);
2898         return ts;
2899 }
2900
2901 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2902 {
2903         struct tonepair_state *ts = data;
2904         int x;
2905
2906         /* we need to prepare a frame with 16 * timelen samples as we're 
2907          * generating SLIN audio
2908          */
2909         len = samples * 2;
2910
2911         if (len > sizeof(ts->data) / 2 - 1) {
2912                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2913                 return -1;
2914         }
2915         memset(&ts->f, 0, sizeof(ts->f));
2916         for (x=0;x<len/2;x++) {
2917                 ts->data[x] = ts->vol * (
2918                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2919                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2920                         );
2921         }
2922         ts->f.frametype = AST_FRAME_VOICE;
2923         ts->f.subclass = AST_FORMAT_SLINEAR;
2924         ts->f.datalen = len;
2925         ts->f.samples = samples;
2926         ts->f.offset = AST_FRIENDLY_OFFSET;
2927         ts->f.data = ts->data;
2928         ast_write(chan, &ts->f);
2929         ts->pos += x;
2930         if (ts->duration > 0) {
2931                 if (ts->pos >= ts->duration * 8)
2932                         return -1;
2933         }
2934         return 0;
2935 }
2936
2937 static struct ast_generator tonepair = {
2938         alloc: tonepair_alloc,
2939         release: tonepair_release,
2940         generate: tonepair_generator,
2941 };
2942
2943 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2944 {
2945         struct tonepair_def d = { 0, };
2946         d.freq1 = freq1;
2947         d.freq2 = freq2;
2948         d.duration = duration;
2949         if (vol < 1)
2950                 d.vol = 8192;
2951         else
2952                 d.vol = vol;
2953         if (ast_activate_generator(chan, &tonepair, &d))
2954                 return -1;
2955         return 0;
2956 }
2957
2958 void ast_tonepair_stop(struct ast_channel *chan)
2959 {
2960         ast_deactivate_generator(chan);
2961 }
2962
2963 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2964 {
2965         struct ast_frame *f;
2966         int res;
2967         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2968                 return res;
2969
2970         /* Give us some wiggle room */
2971         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2972                 f = ast_read(chan);
2973                 if (f)
2974                         ast_frfree(f);
2975                 else
2976                         return -1;
2977         }
2978         return 0;
2979 }
2980
2981 unsigned int ast_get_group(char *s)
2982 {
2983         char *copy;
2984         char *piece;
2985         char *c=NULL;
2986         int start=0, finish=0,x;
2987         unsigned int group = 0;
2988         copy = ast_strdupa(s);
2989         if (!copy) {
2990                 ast_log(LOG_ERROR, "Out of memory\n");
2991                 return 0;
2992         }
2993         c = copy;
2994         
2995         while((piece = strsep(&c, ","))) {
2996                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
2997                         /* Range */
2998                 } else if (sscanf(piece, "%d", &start)) {
2999                         /* Just one */
3000                         finish = start;
3001                 } else {
3002                         ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'.  Using '0'\n", s,piece);
3003                         return 0;
3004                 }
3005                 for (x=start;x<=finish;x++) {
3006                         if ((x > 31) || (x < 0)) {
3007                                 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 31)\n", x);
3008                         } else
3009                                 group |= (1 << x);
3010                 }
3011         }
3012         return group;
3013 }
3014
3015 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
3016 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3017 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3018
3019
3020 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
3021                                                                  void (*stop_ptr)(struct ast_channel *),
3022                                                                  void (*cleanup_ptr)(struct ast_channel *)
3023                                                                  ) 
3024 {
3025         ast_moh_start_ptr = start_ptr;
3026         ast_moh_stop_ptr = stop_ptr;
3027         ast_moh_cleanup_ptr = cleanup_ptr;
3028 }
3029
3030 void ast_uninstall_music_functions(void) 
3031 {
3032         ast_moh_start_ptr = NULL;
3033         ast_moh_stop_ptr = NULL;
3034         ast_moh_cleanup_ptr = NULL;
3035 }
3036
3037 /*! Turn on/off music on hold on a given channel */
3038
3039 int ast_moh_start(struct ast_channel *chan, char *mclass) 
3040 {
3041         if(ast_moh_start_ptr)
3042                 return ast_moh_start_ptr(chan, mclass);
3043
3044         if (option_verbose > 2)
3045                 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3046         
3047         return 0;
3048 }
3049
3050 void ast_moh_stop(struct ast_channel *chan) 
3051 {
3052         if(ast_moh_stop_ptr)
3053                 ast_moh_stop_ptr(chan);
3054 }
3055
3056 void ast_moh_cleanup(struct ast_channel *chan) 
3057 {
3058         if(ast_moh_cleanup_ptr)
3059         ast_moh_cleanup_ptr(chan);
3060 }
3061
3062 void ast_channels_init(void)
3063 {
3064         ast_cli_register(&cli_show_channeltypes);
3065 }