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