e6f0e98ae9728ede6dc16001ecca495d59cd27fa
[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                 /* ADPCM has great sound quality and is still pretty easy to translate */
237                 AST_FORMAT_ADPCM,
238                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
239                    translate and sounds pretty good */
240                 AST_FORMAT_GSM,
241                 /* iLBC is not too bad */
242                 AST_FORMAT_ILBC,
243                 /* Speex is free, but computationally more expensive than GSM */
244                 AST_FORMAT_SPEEX,
245                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
246                    to use it */
247                 AST_FORMAT_LPC10,
248                 /* G.729a is faster than 723 and slightly less expensive */
249                 AST_FORMAT_G729A,
250                 /* Down to G.723.1 which is proprietary but at least designed for voice */
251                 AST_FORMAT_G723_1,
252                 /* Last and least, MP3 which was of course never designed for real-time voice */
253                 AST_FORMAT_MP3,
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         chan = backends;
688         while(chan) {
689                 if (!strcasecmp(chan->type, type)) {
690                         if (last)
691                                 last->next = chan->next;
692                         else
693                                 backends = backends->next;
694                         free(chan);
695                         ast_mutex_unlock(&chlock);
696                         return;
697                 }
698                 last = chan;
699                 chan = chan->next;
700         }
701         ast_mutex_unlock(&chlock);
702 }
703
704 int ast_answer(struct ast_channel *chan)
705 {
706         int res = 0;
707         /* Stop if we're a zombie or need a soft hangup */
708         if (chan->zombie || ast_check_hangup(chan)) 
709                 return -1;
710         switch(chan->_state) {
711         case AST_STATE_RINGING:
712         case AST_STATE_RING:
713                 ast_mutex_lock(&chan->lock);
714                 if (chan->pvt->answer)
715                         res = chan->pvt->answer(chan);
716                 ast_mutex_unlock(&chan->lock);
717                 ast_setstate(chan, AST_STATE_UP);
718                 if (chan->cdr)
719                         ast_cdr_answer(chan->cdr);
720                 return res;
721                 break;
722         case AST_STATE_UP:
723                 if (chan->cdr)
724                         ast_cdr_answer(chan->cdr);
725                 break;
726         }
727         return 0;
728 }
729
730 void ast_deactivate_generator(struct ast_channel *chan)
731 {
732         if (chan->generatordata) {
733                 chan->generator->release(chan, chan->generatordata);
734                 chan->generatordata = NULL;
735                 chan->generator = NULL;
736                 chan->writeinterrupt = 0;
737         }
738 }
739
740 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
741 {
742         if (chan->generatordata) {
743                 chan->generator->release(chan, chan->generatordata);
744                 chan->generatordata = NULL;
745         }
746         ast_prod(chan);
747         if ((chan->generatordata = gen->alloc(chan, params))) {
748                 chan->generator = gen;
749         } else {
750                 return -1;
751         }
752         return 0;
753 }
754
755 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
756 {
757         /* Wait for x amount of time on a file descriptor to have input.  */
758         struct timeval tv;
759         fd_set rfds, efds;
760         int res;
761         int x, max=-1;
762         int winner = -1;
763         
764         tv.tv_sec = *ms / 1000;
765         tv.tv_usec = (*ms % 1000) * 1000;
766         FD_ZERO(&rfds);
767         FD_ZERO(&efds);
768         for (x=0;x<n;x++) {
769                 if (fds[x] > -1) {
770                         FD_SET(fds[x], &rfds);
771                         FD_SET(fds[x], &efds);
772                         if (fds[x] > max)
773                                 max = fds[x];
774                 }
775         }
776         if (*ms >= 0)
777                 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
778         else
779                 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
780
781         if (res < 0) {
782                 /* Simulate a timeout if we were interrupted */
783                 if (errno != EINTR)
784                         *ms = -1;
785                 else
786                         *ms = 0;
787                 return -1;
788         }
789
790         for (x=0;x<n;x++) {
791                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
792                         if (exception)
793                                 *exception = FD_ISSET(fds[x], &efds);
794                         winner = fds[x];
795                 }
796         }
797         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
798         return winner;
799 }
800
801 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
802         int *exception, int *outfd, int *ms)
803 {
804         /* Wait for x amount of time on a file descriptor to have input.  */
805         struct timeval tv;
806         fd_set rfds, efds;
807         int res;
808         int x, y, max=-1;
809         struct ast_channel *winner = NULL;
810         if (outfd)
811                 *outfd = -1;
812         if (exception)
813                 *exception = 0;
814         
815         /* Perform any pending masquerades */
816         for (x=0;x<n;x++) {
817                 ast_mutex_lock(&c[x]->lock);
818                 if (c[x]->masq) {
819                         if (ast_do_masquerade(c[x])) {
820                                 ast_log(LOG_WARNING, "Masquerade failed\n");
821                                 *ms = -1;
822                                 ast_mutex_unlock(&c[x]->lock);
823                                 return NULL;
824                         }
825                 }
826                 ast_mutex_unlock(&c[x]->lock);
827         }
828         
829         tv.tv_sec = *ms / 1000;
830         tv.tv_usec = (*ms % 1000) * 1000;
831         FD_ZERO(&rfds);
832         FD_ZERO(&efds);
833
834         for (x=0;x<n;x++) {
835                 for (y=0;y<AST_MAX_FDS;y++) {
836                         if (c[x]->fds[y] > -1) {
837                                 FD_SET(c[x]->fds[y], &rfds);
838                                 FD_SET(c[x]->fds[y], &efds);
839                                 if (c[x]->fds[y] > max)
840                                         max = c[x]->fds[y];
841                         }
842                 }
843                 CHECK_BLOCKING(c[x]);
844         }
845         for (x=0;x<nfds; x++) {
846                 FD_SET(fds[x], &rfds);
847                 FD_SET(fds[x], &efds);
848                 if (fds[x] > max)
849                         max = fds[x];
850         }
851         if (*ms >= 0)
852                 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
853         else
854                 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
855
856         if (res < 0) {
857                 for (x=0;x<n;x++) 
858                         c[x]->blocking = 0;
859                 /* Simulate a timeout if we were interrupted */
860                 if (errno != EINTR)
861                         *ms = -1;
862                 else {
863                         /* Just an interrupt */
864 #if 0
865                         *ms = 0;
866 #endif                  
867                 }
868                 return NULL;
869         }
870
871         for (x=0;x<n;x++) {
872                 c[x]->blocking = 0;
873                 for (y=0;y<AST_MAX_FDS;y++) {
874                         if (c[x]->fds[y] > -1) {
875                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
876                                         /* Set exception flag if appropriate */
877                                         if (FD_ISSET(c[x]->fds[y], &efds))
878                                                 c[x]->exception = 1;
879                                         c[x]->fdno = y;
880                                         winner = c[x];
881                                 }
882                         }
883                 }
884         }
885         for (x=0;x<nfds;x++) {
886                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
887                         if (outfd)
888                                 *outfd = fds[x];
889                         if (FD_ISSET(fds[x], &efds) && exception)
890                                 *exception = 1;
891                         winner = NULL;
892                 }
893         }
894         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
895         return winner;
896 }
897
898 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
899 {
900         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
901 }
902
903 int ast_waitfor(struct ast_channel *c, int ms)
904 {
905         struct ast_channel *chan;
906         int oldms = ms;
907         chan = ast_waitfor_n(&c, 1, &ms);
908         if (ms < 0) {
909                 if (oldms < 0)
910                         return 0;
911                 else
912                         return -1;
913         }
914         return ms;
915 }
916
917 char ast_waitfordigit(struct ast_channel *c, int ms)
918 {
919         /* XXX Should I be merged with waitfordigit_full XXX */
920         struct ast_frame *f;
921         char result = 0;
922         /* Stop if we're a zombie or need a soft hangup */
923         if (c->zombie || ast_check_hangup(c)) 
924                 return -1;
925         /* Wait for a digit, no more than ms milliseconds total. */
926         while(ms && !result) {
927                 ms = ast_waitfor(c, ms);
928                 if (ms < 0) /* Error */
929                         result = -1; 
930                 else if (ms > 0) {
931                         /* Read something */
932                         f = ast_read(c);
933                         if (f) {
934                                 if (f->frametype == AST_FRAME_DTMF) 
935                                         result = f->subclass;
936                                 ast_frfree(f);
937                         } else
938                                 result = -1;
939                 }
940         }
941         return result;
942 }
943
944 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
945 {
946         int res = -1;
947 #ifdef ZAPTEL_OPTIMIZATIONS
948         if (c->timingfd > -1) {
949                 if (!func) {
950                         samples = 0;
951                         data = 0;
952                 }
953                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
954                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
955                 c->timingfunc = func;
956                 c->timingdata = data;
957         }
958 #endif  
959         return res;
960 }
961 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
962 {
963         struct ast_frame *f;
964         char result = 0;
965         struct ast_channel *rchan;
966         int outfd;
967         /* Stop if we're a zombie or need a soft hangup */
968         if (c->zombie || ast_check_hangup(c)) 
969                 return -1;
970         /* Wait for a digit, no more than ms milliseconds total. */
971         while(ms && !result) {
972                 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
973                 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
974                         result = -1; 
975                 else if (outfd > -1) {
976                         result = 1;
977                 } else if (rchan) {
978                         /* Read something */
979                         f = ast_read(c);
980                         if (f) {
981                                 if (f->frametype == AST_FRAME_DTMF) 
982                                         result = f->subclass;
983                                 ast_frfree(f);
984                         } else
985                                 result = -1;
986                 }
987         }
988         return result;
989 }
990
991 struct ast_frame *ast_read(struct ast_channel *chan)
992 {
993         struct ast_frame *f = NULL;
994         int blah;
995 #ifdef ZAPTEL_OPTIMIZATIONS
996         int (*func)(void *);
997         void *data;
998 #endif
999         static struct ast_frame null_frame = 
1000         {
1001                 AST_FRAME_NULL,
1002         };
1003         
1004         ast_mutex_lock(&chan->lock);
1005         if (chan->masq) {
1006                 if (ast_do_masquerade(chan)) {
1007                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1008                         f = NULL;
1009                 } else
1010                         f =  &null_frame;
1011                 ast_mutex_unlock(&chan->lock);
1012                 return f;
1013         }
1014
1015         /* Stop if we're a zombie or need a soft hangup */
1016         if (chan->zombie || ast_check_hangup(chan)) {
1017                 if (chan->generator)
1018                         ast_deactivate_generator(chan);
1019                 ast_mutex_unlock(&chan->lock);
1020                 return NULL;
1021         }
1022
1023         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
1024                 /* We have DTMF that has been deferred.  Return it now */
1025                 chan->dtmff.frametype = AST_FRAME_DTMF;
1026                 chan->dtmff.subclass = chan->dtmfq[0];
1027                 /* Drop first digit */
1028                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1029                 ast_mutex_unlock(&chan->lock);
1030                 return &chan->dtmff;
1031         }
1032         
1033         /* Read and ignore anything on the alertpipe, but read only
1034            one sizeof(blah) per frame that we send from it */
1035         if (chan->pvt->alertpipe[0] > -1) {
1036                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1037         }
1038 #ifdef ZAPTEL_OPTIMIZATIONS
1039         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && chan->exception) {
1040                 chan->exception = 0;
1041                 blah = -1;
1042                 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1043                 func = chan->timingfunc;
1044                 data = chan->timingdata;
1045                 ast_mutex_unlock(&chan->lock);
1046                 if (func) {
1047 #if 0
1048                         ast_log(LOG_DEBUG, "Calling private function\n");
1049 #endif                  
1050                         func(data);
1051                 } else {
1052                         blah = 0;
1053                         ast_mutex_lock(&chan->lock);
1054                         ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1055                         chan->timingdata = NULL;
1056                         ast_mutex_unlock(&chan->lock);
1057                 }
1058                 f =  &null_frame;
1059                 return f;
1060         }
1061 #endif
1062         /* Check for pending read queue */
1063         if (chan->pvt->readq) {
1064                 f = chan->pvt->readq;
1065                 chan->pvt->readq = f->next;
1066                 /* Interpret hangup and return NULL */
1067                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
1068                         f = NULL;
1069         } else {
1070                 chan->blocker = pthread_self();
1071                 if (chan->exception) {
1072                         if (chan->pvt->exception) 
1073                                 f = chan->pvt->exception(chan);
1074                         else {
1075                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1076                                 f = &null_frame;
1077                         }
1078                         /* Clear the exception flag */
1079                         chan->exception = 0;
1080                 } else
1081                 if (chan->pvt->read)
1082                         f = chan->pvt->read(chan);
1083                 else
1084                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1085         }
1086
1087
1088         if (f && (f->frametype == AST_FRAME_VOICE)) {
1089                 if (!(f->subclass & chan->nativeformats)) {
1090                         /* This frame can't be from the current native formats -- drop it on the
1091                            floor */
1092                         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));
1093                         ast_frfree(f);
1094                         f = &null_frame;
1095                 } else {
1096                         if (chan->monitor && chan->monitor->read_stream ) {
1097 #ifndef MONITOR_CONSTANT_DELAY
1098                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1099                                 if (jump >= 0) {
1100                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1101                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1102                                         chan->insmpl += jump + 2 * f->samples;
1103                                 } else
1104                                         chan->insmpl+= f->samples;
1105 #else
1106                                 int jump = chan->outsmpl - chan->insmpl;
1107                                 if (jump - MONITOR_DELAY >= 0) {
1108                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1109                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1110                                         chan->insmpl += jump;
1111                                 } else
1112                                         chan->insmpl += f->samples;
1113 #endif
1114                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1115                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1116                         }
1117                         if (chan->pvt->readtrans) {
1118                                 f = ast_translate(chan->pvt->readtrans, f, 1);
1119                                 if (!f)
1120                                         f = &null_frame;
1121                         }
1122                 }
1123         }
1124
1125         /* Make sure we always return NULL in the future */
1126         if (!f) {
1127                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1128                 if (chan->generator)
1129                         ast_deactivate_generator(chan);
1130                 /* End the CDR if appropriate */
1131                 if (chan->cdr)
1132                         ast_cdr_end(chan->cdr);
1133         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1134                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1135                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1136                 else
1137                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1138                 f = &null_frame;
1139         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1140                 /* Answer the CDR */
1141                 ast_setstate(chan, AST_STATE_UP);
1142                 ast_cdr_answer(chan->cdr);
1143         } 
1144         ast_mutex_unlock(&chan->lock);
1145
1146         /* Run any generator sitting on the line */
1147         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1148                 /* Mask generator data temporarily */
1149                 void *tmp;
1150                 int res;
1151                 tmp = chan->generatordata;
1152                 chan->generatordata = NULL;
1153                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1154                 chan->generatordata = tmp;
1155                 if (res) {
1156                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1157                         ast_deactivate_generator(chan);
1158                 }
1159         }
1160         if (chan->fin & 0x80000000)
1161                 ast_frame_dump(chan->name, f, "<<");
1162         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1163                 chan->fin &= 0x80000000;
1164         else
1165                 chan->fin++;
1166         return f;
1167 }
1168
1169 int ast_indicate(struct ast_channel *chan, int condition)
1170 {
1171         int res = -1;
1172         /* Stop if we're a zombie or need a soft hangup */
1173         if (chan->zombie || ast_check_hangup(chan)) 
1174                 return -1;
1175         ast_mutex_lock(&chan->lock);
1176         if (chan->pvt->indicate)
1177                 res = chan->pvt->indicate(chan, condition);
1178         ast_mutex_unlock(&chan->lock);
1179         if (!chan->pvt->indicate || res) {
1180                 /*
1181                  * Device does not support (that) indication, lets fake
1182                  * it by doing our own tone generation. (PM2002)
1183                  */
1184                 if (condition >= 0) {
1185                         const struct tone_zone_sound *ts = NULL;
1186                         switch (condition) {
1187                          case AST_CONTROL_RINGING:
1188                                 ts = ast_get_indication_tone(chan->zone, "ring");
1189                                 break;
1190                          case AST_CONTROL_BUSY:
1191                                 ts = ast_get_indication_tone(chan->zone, "busy");
1192                                 break;
1193                          case AST_CONTROL_CONGESTION:
1194                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1195                                 break;
1196                         }
1197                         if (ts && ts->data[0]) {
1198                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1199                                 ast_playtones_start(chan,0,ts->data, 1);
1200                                 res = 0;
1201                         } else if (condition == AST_CONTROL_PROGRESS) {
1202                                 /* ast_playtones_stop(chan); */
1203                         } else {
1204                                 /* not handled */
1205                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1206                                 res = -1;
1207                         }
1208                 }
1209                 else ast_playtones_stop(chan);
1210         }
1211         return res;
1212 }
1213
1214 int ast_recvchar(struct ast_channel *chan, int timeout)
1215 {
1216         int res,ourto,c;
1217         struct ast_frame *f;
1218         
1219         ourto = timeout;
1220         for(;;)
1221            {
1222                 if (ast_check_hangup(chan)) return -1;
1223                 res = ast_waitfor(chan,ourto);
1224                 if (res <= 0) /* if timeout */
1225                    {
1226                         return 0;
1227                    }
1228                 ourto = res;
1229                 f = ast_read(chan);
1230                 if (f == NULL) return -1; /* if hangup */
1231                 if ((f->frametype == AST_FRAME_CONTROL) &&
1232                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1233                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1234                    {
1235                         c = *((char *)f->data);  /* get the data */
1236                         ast_frfree(f);
1237                         return(c);
1238                    }
1239                 ast_frfree(f);
1240         }
1241 }
1242
1243 int ast_sendtext(struct ast_channel *chan, char *text)
1244 {
1245         int res = 0;
1246         /* Stop if we're a zombie or need a soft hangup */
1247         if (chan->zombie || ast_check_hangup(chan)) 
1248                 return -1;
1249         CHECK_BLOCKING(chan);
1250         if (chan->pvt->send_text)
1251                 res = chan->pvt->send_text(chan, text);
1252         chan->blocking = 0;
1253         return res;
1254 }
1255
1256 static int do_senddigit(struct ast_channel *chan, char digit)
1257 {
1258         int res = -1;
1259
1260         if (chan->pvt->send_digit)
1261                 res = chan->pvt->send_digit(chan, digit);
1262         if (!chan->pvt->send_digit || res) {
1263                 /*
1264                  * Device does not support DTMF tones, lets fake
1265                  * it by doing our own generation. (PM2002)
1266                  */
1267                 static const char* dtmf_tones[] = {
1268                         "!941+1336/50,!0/50",   /* 0 */
1269                         "!697+1209/50,!0/50",   /* 1 */
1270                         "!697+1336/50,!0/50",   /* 2 */
1271                         "!697+1477/50,!0/50",   /* 3 */
1272                         "!770+1209/50,!0/50",   /* 4 */
1273                         "!770+1336/50,!0/50",   /* 5 */
1274                         "!770+1477/50,!0/50",   /* 6 */
1275                         "!852+1209/50,!0/50",   /* 7 */
1276                         "!852+1336/50,!0/50",   /* 8 */
1277                         "!852+1477/50,!0/50",   /* 9 */
1278                         "!697+1633/50,!0/50",   /* A */
1279                         "!770+1633/50,!0/50",   /* B */
1280                         "!852+1633/50,!0/50",   /* C */
1281                         "!941+1633/50,!0/50",   /* D */
1282                         "!941+1209/50,!0/50",   /* * */
1283                         "!941+1477/50,!0/50" }; /* # */
1284                 if (digit >= '0' && digit <='9')
1285                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1286                 else if (digit >= 'A' && digit <= 'D')
1287                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1288                 else if (digit == '*')
1289                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1290                 else if (digit == '#')
1291                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1292                 else {
1293                         /* not handled */
1294                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1295                         return -1;
1296                 }
1297         }
1298         return 0;
1299 }
1300
1301 int ast_prod(struct ast_channel *chan)
1302 {
1303         struct ast_frame a = { AST_FRAME_VOICE };
1304         char nothing[128];
1305         /* Send an empty audio frame to get things moving */
1306         if (chan->_state != AST_STATE_UP) {
1307                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1308                 a.subclass = chan->pvt->rawwriteformat;
1309                 a.data = nothing + AST_FRIENDLY_OFFSET;
1310                 if (ast_write(chan, &a))
1311                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1312         }
1313         return 0;
1314 }
1315
1316 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1317 {
1318         int res;
1319         if (!chan->pvt->write_video)
1320                 return 0;
1321         res = ast_write(chan, fr);
1322         if (!res)
1323                 res = 1;
1324         return res;
1325 }
1326
1327 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1328 {
1329         int res = -1;
1330         struct ast_frame *f = NULL;
1331         /* Stop if we're a zombie or need a soft hangup */
1332         ast_mutex_lock(&chan->lock);
1333         if (chan->zombie || ast_check_hangup(chan))  {
1334                 ast_mutex_unlock(&chan->lock);
1335                 return -1;
1336         }
1337         /* Handle any pending masquerades */
1338         if (chan->masq) {
1339                 if (ast_do_masquerade(chan)) {
1340                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1341                         ast_mutex_unlock(&chan->lock);
1342                         return -1;
1343                 }
1344         }
1345         if (chan->masqr) {
1346                 ast_mutex_unlock(&chan->lock);
1347                 return 0;
1348         }
1349         if (chan->generatordata) {
1350                 if (chan->writeinterrupt)
1351                         ast_deactivate_generator(chan);
1352                 else {
1353                         ast_mutex_unlock(&chan->lock);
1354                         return 0;
1355                 }
1356         }
1357         if (chan->fout & 0x80000000)
1358                 ast_frame_dump(chan->name, fr, ">>");
1359         CHECK_BLOCKING(chan);
1360         switch(fr->frametype) {
1361         case AST_FRAME_CONTROL:
1362                 /* XXX Interpret control frames XXX */
1363                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1364                 break;
1365         case AST_FRAME_DTMF:
1366                 chan->blocking = 0;
1367                 ast_mutex_unlock(&chan->lock);
1368                 res = do_senddigit(chan,fr->subclass);
1369                 ast_mutex_lock(&chan->lock);
1370                 CHECK_BLOCKING(chan);
1371                 break;
1372         case AST_FRAME_TEXT:
1373                 if (chan->pvt->send_text)
1374                         res = chan->pvt->send_text(chan, (char *) fr->data);
1375                 break;
1376         case AST_FRAME_VIDEO:
1377                 /* XXX Handle translation of video codecs one day XXX */
1378                 if (chan->pvt->write_video)
1379                         res = chan->pvt->write_video(chan, fr);
1380                 else
1381                         res = 0;
1382                 break;
1383         default:
1384                 if (chan->pvt->write) {
1385                         if (chan->pvt->writetrans) {
1386                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1387                         } else
1388                                 f = fr;
1389                         if (f) {
1390                                 res = chan->pvt->write(chan, f);
1391                                 if( chan->monitor &&
1392                                                 chan->monitor->write_stream &&
1393                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1394 #ifndef MONITOR_CONSTANT_DELAY
1395                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1396                                         if (jump >= 0) {
1397                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1398                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1399                                                 chan->outsmpl += jump + 2 * f->samples;
1400                                         } else
1401                                                 chan->outsmpl += f->samples;
1402 #else
1403                                         int jump = chan->insmpl - chan->outsmpl;
1404                                         if (jump - MONITOR_DELAY >= 0) {
1405                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1406                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1407                                                 chan->outsmpl += jump;
1408                                         } else
1409                                                 chan->outsmpl += f->samples;
1410 #endif
1411                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1412                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1413                                 }
1414                         } else
1415                                 res = 0;
1416                 }
1417         }
1418         if (f && (f != fr))
1419                 ast_frfree(f);
1420         chan->blocking = 0;
1421         /* Consider a write failure to force a soft hangup */
1422         if (res < 0)
1423                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1424         else {
1425                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1426                         chan->fout &= 0x80000000;
1427                 else
1428                         chan->fout++;
1429                 chan->fout++;
1430         }
1431         ast_mutex_unlock(&chan->lock);
1432         return res;
1433 }
1434
1435 int ast_set_write_format(struct ast_channel *chan, int fmts)
1436 {
1437         int fmt;
1438         int native;
1439         int res;
1440         
1441         native = chan->nativeformats;
1442         fmt = fmts;
1443         
1444         res = ast_translator_best_choice(&native, &fmt);
1445         if (res < 0) {
1446                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1447                         ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1448                 return -1;
1449         }
1450         
1451         /* Now we have a good choice for both.  We'll write using our native format. */
1452         chan->pvt->rawwriteformat = native;
1453         /* User perspective is fmt */
1454         chan->writeformat = fmt;
1455         /* Free any write translation we have right now */
1456         if (chan->pvt->writetrans)
1457                 ast_translator_free_path(chan->pvt->writetrans);
1458         /* Build a translation path from the user write format to the raw writing format */
1459         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1460         if (option_debug)
1461                 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1462         return 0;
1463 }
1464
1465 int ast_set_read_format(struct ast_channel *chan, int fmts)
1466 {
1467         int fmt;
1468         int native;
1469         int res;
1470         
1471         native = chan->nativeformats;
1472         fmt = fmts;
1473         /* Find a translation path from the native read format to one of the user's read formats */
1474         res = ast_translator_best_choice(&fmt, &native);
1475         if (res < 0) {
1476                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1477                         ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1478                 return -1;
1479         }
1480         
1481         /* Now we have a good choice for both.  We'll write using our native format. */
1482         chan->pvt->rawreadformat = native;
1483         /* User perspective is fmt */
1484         chan->readformat = fmt;
1485         /* Free any read translation we have right now */
1486         if (chan->pvt->readtrans)
1487                 ast_translator_free_path(chan->pvt->readtrans);
1488         /* Build a translation path from the raw read format to the user reading format */
1489         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1490         if (option_debug)
1491                 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n", 
1492                         chan->name, ast_getformatname(chan->readformat));
1493         return 0;
1494 }
1495
1496 struct ast_channel *__ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid, struct outgoing_helper *oh)
1497 {
1498         int state = 0;
1499         struct ast_channel *chan;
1500         struct ast_frame *f;
1501         int res = 0;
1502         chan = ast_request(type, format, data);
1503         if (chan) {
1504                 if (oh) {
1505                         char *tmp, *var;
1506                         /* JDG chanvar */
1507                         tmp = oh->variable;
1508                         /* FIXME replace this call with strsep  NOT*/
1509                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1510                                 pbx_builtin_setvar( chan, var );
1511                         } /* /JDG */
1512                         if (*oh->context)
1513                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1514                         if (*oh->exten)
1515                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1516                         if (*oh->callerid)
1517                                 ast_set_callerid(chan, oh->callerid, 1);
1518                         chan->priority = oh->priority;
1519                 }
1520                 if (callerid && strlen(callerid))
1521                         ast_set_callerid(chan, callerid, 1);
1522
1523                 if (!ast_call(chan, data, 0)) {
1524                         while(timeout && (chan->_state != AST_STATE_UP)) {
1525                                 res = ast_waitfor(chan, timeout);
1526                                 if (res < 0) {
1527                                         /* Something not cool, or timed out */
1528                                         break;
1529                                 }
1530                                 /* If done, break out */
1531                                 if (!res)
1532                                         break;
1533                                 if (timeout > -1)
1534                                         timeout = res;
1535                                 f = ast_read(chan);
1536                                 if (!f) {
1537                                         state = AST_CONTROL_HANGUP;
1538                                         res = 0;
1539                                         break;
1540                                 }
1541                                 if (f->frametype == AST_FRAME_CONTROL) {
1542                                         if (f->subclass == AST_CONTROL_RINGING)
1543                                                 state = AST_CONTROL_RINGING;
1544                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1545                                                 state = f->subclass;
1546                                                 ast_frfree(f);
1547                                                 break;
1548                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1549                                                 state = f->subclass;
1550                                                 ast_frfree(f);
1551                                                 break;
1552                                         } else {
1553                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1554                                         }
1555                                 }
1556                                 ast_frfree(f);
1557                         }
1558                 } else
1559                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1560         } else
1561                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1562         if (chan && (chan->_state == AST_STATE_UP))
1563                 state = AST_CONTROL_ANSWER;
1564         if (outstate)
1565                 *outstate = state;
1566         if (chan && res <= 0) {
1567                 if (!chan->cdr) {
1568                         chan->cdr = ast_cdr_alloc();
1569                         if (chan->cdr)
1570                                 ast_cdr_init(chan->cdr, chan);
1571                 }
1572                 if (chan->cdr) {
1573                         char tmp[256];
1574                         sprintf(tmp, "%s/%s",type,(char *)data);
1575                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1576                         ast_cdr_update(chan);
1577                         ast_cdr_start(chan->cdr);
1578                         ast_cdr_end(chan->cdr);
1579                         /* If the cause wasn't handled properly */
1580                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1581                                 ast_cdr_failed(chan->cdr);
1582                 } else 
1583                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1584                 ast_hangup(chan);
1585                 chan = NULL;
1586         }
1587         return chan;
1588 }
1589
1590 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1591 {
1592         return __ast_request_and_dial(type, format, data, timeout, outstate, callerid, NULL);
1593 }
1594
1595 struct ast_channel *ast_request(char *type, int format, void *data)
1596 {
1597         struct chanlist *chan;
1598         struct ast_channel *c = NULL;
1599         int capabilities;
1600         int fmt;
1601         int res;
1602         if (ast_mutex_lock(&chlock)) {
1603                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1604                 return NULL;
1605         }
1606         chan = backends;
1607         while(chan) {
1608                 if (!strcasecmp(type, chan->type)) {
1609                         capabilities = chan->capabilities;
1610                         fmt = format;
1611                         res = ast_translator_best_choice(&fmt, &capabilities);
1612                         if (res < 0) {
1613                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1614                                 ast_mutex_unlock(&chlock);
1615                                 return NULL;
1616                         }
1617                         ast_mutex_unlock(&chlock);
1618                         if (chan->requester)
1619                                 c = chan->requester(type, capabilities, data);
1620                         if (c) {
1621                                 if (c->_state == AST_STATE_DOWN) {
1622                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1623                                         "Channel: %s\r\n"
1624                                         "State: %s\r\n"
1625                                         "Callerid: %s\r\n"
1626                                         "Uniqueid: %s\r\n",
1627                                         c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1628                                 }
1629                         }
1630                         return c;
1631                 }
1632                 chan = chan->next;
1633         }
1634         if (!chan)
1635                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1636         ast_mutex_unlock(&chlock);
1637         return c;
1638 }
1639
1640 int ast_parse_device_state(char *device)
1641 {
1642         char name[AST_CHANNEL_NAME] = "";
1643         char *cut;
1644         struct ast_channel *chan;
1645
1646         chan = ast_channel_walk(NULL);
1647         while (chan) {
1648                 strncpy(name, chan->name, sizeof(name)-1);
1649                 cut = strchr(name,'-');
1650                 if (cut)
1651                         *cut = 0;
1652                 if (!strcmp(name, device))
1653                         return AST_DEVICE_INUSE;
1654                 chan = ast_channel_walk(chan);
1655         }
1656         return AST_DEVICE_UNKNOWN;
1657 }
1658
1659 int ast_device_state(char *device)
1660 {
1661         char tech[AST_MAX_EXTENSION] = "";
1662         char *number;
1663         struct chanlist *chanls;
1664         int res = 0;
1665         
1666         strncpy(tech, device, sizeof(tech)-1);
1667         number = strchr(tech, '/');
1668         if (!number) {
1669             return AST_DEVICE_INVALID;
1670         }
1671         *number = 0;
1672         number++;
1673                 
1674         if (ast_mutex_lock(&chlock)) {
1675                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1676                 return -1;
1677         }
1678         chanls = backends;
1679         while(chanls) {
1680                 if (!strcasecmp(tech, chanls->type)) {
1681                         ast_mutex_unlock(&chlock);
1682                         if (!chanls->devicestate) 
1683                                 return ast_parse_device_state(device);
1684                         else {
1685                                 res = chanls->devicestate(number);
1686                                 if (res == AST_DEVICE_UNKNOWN)
1687                                         return ast_parse_device_state(device);
1688                                 else
1689                                         return res;
1690                         }
1691                 }
1692                 chanls = chanls->next;
1693         }
1694         ast_mutex_unlock(&chlock);
1695         return AST_DEVICE_INVALID;
1696 }
1697
1698 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1699 {
1700         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1701            If the remote end does not answer within the timeout, then do NOT hang up, but 
1702            return anyway.  */
1703         int res = -1;
1704         /* Stop if we're a zombie or need a soft hangup */
1705         ast_mutex_lock(&chan->lock);
1706         if (!chan->zombie && !ast_check_hangup(chan)) 
1707                 if (chan->pvt->call)
1708                         res = chan->pvt->call(chan, addr, timeout);
1709         ast_mutex_unlock(&chan->lock);
1710         return res;
1711 }
1712
1713 int ast_transfer(struct ast_channel *chan, char *dest) 
1714 {
1715         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1716            If the remote end does not answer within the timeout, then do NOT hang up, but 
1717            return anyway.  */
1718         int res = -1;
1719         /* Stop if we're a zombie or need a soft hangup */
1720         ast_mutex_lock(&chan->lock);
1721         if (!chan->zombie && !ast_check_hangup(chan)) {
1722                 if (chan->pvt->transfer) {
1723                         res = chan->pvt->transfer(chan, dest);
1724                         if (!res)
1725                                 res = 1;
1726                 } else
1727                         res = 0;
1728         }
1729         ast_mutex_unlock(&chan->lock);
1730         return res;
1731 }
1732
1733 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1734 {
1735         int pos=0;
1736         int to = ftimeout;
1737         char d;
1738         /* XXX Merge with full version? XXX */
1739         /* Stop if we're a zombie or need a soft hangup */
1740         if (c->zombie || ast_check_hangup(c)) 
1741                 return -1;
1742         if (!len)
1743                 return -1;
1744         do {
1745                 if (c->stream) {
1746                         d = ast_waitstream(c, AST_DIGIT_ANY);
1747                         ast_stopstream(c);
1748                         usleep(1000);
1749                         if (!d)
1750                                 d = ast_waitfordigit(c, to);
1751                 } else {
1752                         d = ast_waitfordigit(c, to);
1753                 }
1754                 if (d < 0)
1755                         return -1;
1756                 if (d == 0) {
1757                         s[pos]='\0';
1758                         return 1;
1759                 }
1760                 if (!strchr(enders, d))
1761                         s[pos++] = d;
1762                 if (strchr(enders, d) || (pos >= len)) {
1763                         s[pos]='\0';
1764                         return 0;
1765                 }
1766                 to = timeout;
1767         } while(1);
1768         /* Never reached */
1769         return 0;
1770 }
1771
1772 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1773 {
1774         int pos=0;
1775         int to = ftimeout;
1776         char d;
1777         /* Stop if we're a zombie or need a soft hangup */
1778         if (c->zombie || ast_check_hangup(c)) 
1779                 return -1;
1780         if (!len)
1781                 return -1;
1782         do {
1783                 if (c->stream) {
1784                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1785                         ast_stopstream(c);
1786                         usleep(1000);
1787                         if (!d)
1788                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1789                 } else {
1790                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1791                 }
1792                 if (d < 0)
1793                         return -1;
1794                 if (d == 0) {
1795                         s[pos]='\0';
1796                         return 1;
1797                 }
1798                 if (d == 1) {
1799                         s[pos]='\0';
1800                         return 2;
1801                 }
1802                 if (!strchr(enders, d))
1803                         s[pos++] = d;
1804                 if (strchr(enders, d) || (pos >= len)) {
1805                         s[pos]='\0';
1806                         return 0;
1807                 }
1808                 to = timeout;
1809         } while(1);
1810         /* Never reached */
1811         return 0;
1812 }
1813
1814 int ast_channel_supports_html(struct ast_channel *chan)
1815 {
1816         if (chan->pvt->send_html)
1817                 return 1;
1818         return 0;
1819 }
1820
1821 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1822 {
1823         if (chan->pvt->send_html)
1824                 return chan->pvt->send_html(chan, subclass, data, datalen);
1825         return -1;
1826 }
1827
1828 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1829 {
1830         if (chan->pvt->send_html)
1831                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1832         return -1;
1833 }
1834
1835 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1836 {
1837         int peerf;
1838         int chanf;
1839         int res;
1840         peerf = peer->nativeformats;
1841         chanf = chan->nativeformats;
1842         res = ast_translator_best_choice(&peerf, &chanf);
1843         if (res < 0) {
1844                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1845                 return -1;
1846         }
1847         /* Set read format on channel */
1848         res = ast_set_read_format(chan, peerf);
1849         if (res < 0) {
1850                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1851                 return -1;
1852         }
1853         /* Set write format on peer channel */
1854         res = ast_set_write_format(peer, peerf);
1855         if (res < 0) {
1856                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1857                 return -1;
1858         }
1859         /* Now we go the other way */
1860         peerf = peer->nativeformats;
1861         chanf = chan->nativeformats;
1862         res = ast_translator_best_choice(&chanf, &peerf);
1863         if (res < 0) {
1864                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1865                 return -1;
1866         }
1867         /* Set writeformat on channel */
1868         res = ast_set_write_format(chan, chanf);
1869         if (res < 0) {
1870                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1871                 return -1;
1872         }
1873         /* Set read format on peer channel */
1874         res = ast_set_read_format(peer, chanf);
1875         if (res < 0) {
1876                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1877                 return -1;
1878         }
1879         return 0;
1880 }
1881
1882 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1883 {
1884         struct ast_frame null = { AST_FRAME_NULL, };
1885         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1886                 clone->name, original->name);
1887         if (original->masq) {
1888                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1889                         original->masq->name, original->name);
1890                 return -1;
1891         }
1892         if (clone->masqr) {
1893                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1894                         clone->name, clone->masqr->name);
1895                 return -1;
1896         }
1897         original->masq = clone;
1898         clone->masqr = original;
1899         /* XXX can't really hold the lock here, but at the same time, it' s
1900            not really safe not to XXX */
1901         ast_queue_frame(original, &null, 0);
1902         ast_queue_frame(clone, &null, 0);
1903         ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1904         return 0;
1905 }
1906
1907 void ast_change_name(struct ast_channel *chan, char *newname)
1908 {
1909         char tmp[256];
1910         strncpy(tmp, chan->name, 256);
1911         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1912         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
1913 }
1914
1915 static int ast_do_masquerade(struct ast_channel *original)
1916 {
1917         int x,i;
1918         int res=0;
1919         char *tmp;
1920         void *tmpv;
1921         struct ast_frame *cur, *prev;
1922         struct ast_channel_pvt *p;
1923         struct ast_channel *clone = original->masq;
1924         int rformat = original->readformat;
1925         int wformat = original->writeformat;
1926         char newn[100];
1927         char orig[100];
1928         char masqn[100];
1929         char zombn[100];
1930         
1931 #if 1
1932         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1933                 clone->name, clone->_state, original->name, original->_state);
1934 #endif
1935         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1936            the clone channel into the original channel.  Start by killing off the original
1937            channel's backend.   I'm not sure we're going to keep this function, because 
1938            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1939
1940         /* We need the clone's lock, too */
1941         ast_mutex_lock(&clone->lock);
1942
1943         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
1944
1945         /* Having remembered the original read/write formats, we turn off any translation on either
1946            one */
1947         free_translation(clone);
1948         free_translation(original);
1949
1950
1951         /* Unlink the masquerade */
1952         original->masq = NULL;
1953         clone->masqr = NULL;
1954         
1955         /* Save the original name */
1956         strncpy(orig, original->name, sizeof(orig) - 1);
1957         /* Save the new name */
1958         strncpy(newn, clone->name, sizeof(newn) - 1);
1959         /* Create the masq name */
1960         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1961                 
1962         /* Copy the name from the clone channel */
1963         strncpy(original->name, newn, sizeof(original->name)-1);
1964
1965         /* Mangle the name of the clone channel */
1966         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1967         
1968         /* Notify any managers of the change, first the masq then the other */
1969         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1970         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1971
1972         /* Swap the guts */     
1973         p = original->pvt;
1974         original->pvt = clone->pvt;
1975         clone->pvt = p;
1976
1977         /* Save any pending frames on both sides.  Start by counting
1978          * how many we're going to need... */
1979         prev = NULL;
1980         cur = clone->pvt->readq;
1981         x = 0;
1982         while(cur) {
1983                 x++;
1984                 prev = cur;
1985                 cur = cur->next;
1986         }
1987         /* If we had any, prepend them to the ones already in the queue, and 
1988          * load up the alertpipe */
1989         if (prev) {
1990                 prev->next = original->pvt->readq;
1991                 original->pvt->readq = clone->pvt->readq;
1992                 clone->pvt->readq = NULL;
1993                 if (original->pvt->alertpipe[1] > -1) {
1994                         for (i=0;i<x;i++)
1995                                 write(original->pvt->alertpipe[1], &x, sizeof(x));
1996                 }
1997         }
1998         clone->_softhangup = AST_SOFTHANGUP_DEV;
1999
2000
2001         if (clone->pvt->fixup){
2002                 res = clone->pvt->fixup(original, clone);
2003                 if (res) 
2004                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2005         }
2006
2007         /* Start by disconnecting the original's physical side */
2008         if (clone->pvt->hangup)
2009                 res = clone->pvt->hangup(clone);
2010         if (res) {
2011                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2012                 ast_mutex_unlock(&clone->lock);
2013                 return -1;
2014         }
2015         
2016         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2017         /* Mangle the name of the clone channel */
2018         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2019         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
2020
2021         /* Keep the same language.  */
2022         /* Update the type. */
2023         original->type = clone->type;
2024         /* Copy the FD's */
2025         for (x=0;x<AST_MAX_FDS;x++) {
2026                 original->fds[x] = clone->fds[x];
2027         }
2028         /* Move the variables */
2029         tmpv = original->varshead.first;
2030         original->varshead.first = clone->varshead.first;
2031         clone->varshead.first = tmpv;
2032         /* Presense of ADSI capable CPE follows clone */
2033         original->adsicpe = clone->adsicpe;
2034         /* Bridge remains the same */
2035         /* CDR fields remain the same */
2036         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2037         /* Application and data remain the same */
2038         /* Clone exception  becomes real one, as with fdno */
2039         original->exception = clone->exception;
2040         original->fdno = clone->fdno;
2041         /* Schedule context remains the same */
2042         /* Stream stuff stays the same */
2043         /* Keep the original state.  The fixup code will need to work with it most likely */
2044
2045         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
2046            fields back into the defunct 'clone' so that they will be freed when
2047            ast_frfree is eventually called */
2048         tmp = original->dnid;
2049         original->dnid = clone->dnid;
2050         clone->dnid = tmp;
2051         
2052         tmp = original->callerid;
2053         original->callerid = clone->callerid;
2054         clone->callerid = tmp;
2055         
2056         /* Restore original timing file descriptor */
2057         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2058         
2059         /* Our native formats are different now */
2060         original->nativeformats = clone->nativeformats;
2061
2062         /* And of course, so does our current state.  Note we need not
2063            call ast_setstate since the event manager doesn't really consider
2064            these separate */
2065         original->_state = clone->_state;
2066         
2067         /* Context, extension, priority, app data, jump table,  remain the same */
2068         /* pvt switches.  pbx stays the same, as does next */
2069         
2070         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2071            a zombie so nothing tries to touch it.  If it's already been marked as a
2072            zombie, then free it now (since it already is considered invalid). */
2073         if (clone->zombie) {
2074                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2075                 ast_mutex_unlock(&clone->lock);
2076                 ast_channel_free(clone);
2077                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2078         } else {
2079                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2080                 clone->zombie=1;
2081                 ast_mutex_unlock(&clone->lock);
2082         }
2083         /* Set the write format */
2084         ast_set_write_format(original, wformat);
2085
2086         /* Set the read format */
2087         ast_set_read_format(original, rformat);
2088
2089         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2090
2091         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2092            can fix up everything as best as possible */
2093         if (original->pvt->fixup) {
2094                 res = original->pvt->fixup(clone, original);
2095                 if (res) {
2096                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2097                                 original->type, original->name);
2098                         return -1;
2099                 }
2100         } else
2101                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2102                         original->type, original->name);
2103         /* Signal any blocker */
2104         if (original->blocking)
2105                 pthread_kill(original->blocker, SIGURG);
2106         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2107                 original->name, original->_state);
2108         return 0;
2109 }
2110
2111 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2112 {
2113         if (chan->callerid)
2114                 free(chan->callerid);
2115         if (anitoo && chan->ani)
2116                 free(chan->ani);
2117         if (callerid) {
2118                 chan->callerid = strdup(callerid);
2119                 if (anitoo)
2120                         chan->ani = strdup(callerid);
2121         } else {
2122                 chan->callerid = NULL;
2123                 if (anitoo)
2124                         chan->ani = NULL;
2125         }
2126         if (chan->cdr)
2127                 ast_cdr_setcid(chan->cdr, chan);
2128         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2129                                 "Channel: %s\r\n"
2130                                 "Callerid: %s\r\n"
2131                                 "Uniqueid: %s\r\n",
2132                                 chan->name, chan->callerid ? 
2133                                 chan->callerid : "<Unknown>",
2134                                 chan->uniqueid);
2135 }
2136
2137 int ast_setstate(struct ast_channel *chan, int state)
2138 {
2139         if (chan->_state != state) {
2140                 int oldstate = chan->_state;
2141                 chan->_state = state;
2142                 if (oldstate == AST_STATE_DOWN) {
2143                         ast_device_state_changed(chan->name);
2144                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2145                         "Channel: %s\r\n"
2146                         "State: %s\r\n"
2147                         "Callerid: %s\r\n"
2148                         "Uniqueid: %s\r\n",
2149                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2150                 } else {
2151                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2152                                 "Channel: %s\r\n"
2153                                 "State: %s\r\n"
2154                                 "Callerid: %s\r\n"
2155                                 "Uniqueid: %s\r\n",
2156                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2157                 }
2158         }
2159         return 0;
2160 }
2161
2162 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2163 {
2164         /* Copy voice back and forth between the two channels.  Give the peer
2165            the ability to transfer calls with '#<extension' syntax. */
2166         struct ast_channel *cs[3];
2167         int to = -1;
2168         struct ast_frame *f;
2169         struct ast_channel *who = NULL;
2170         int res;
2171         int nativefailed=0;
2172
2173         /* Stop if we're a zombie or need a soft hangup */
2174         if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) 
2175                 return -1;
2176         if (c0->bridge) {
2177                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2178                         c0->name, c0->bridge->name);
2179                 return -1;
2180         }
2181         if (c1->bridge) {
2182                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2183                         c1->name, c1->bridge->name);
2184                 return -1;
2185         }
2186         
2187         /* Keep track of bridge */
2188         c0->bridge = c1;
2189         c1->bridge = c0;
2190         cs[0] = c0;
2191         cs[1] = c1;
2192         
2193         manager_event(EVENT_FLAG_CALL, "Link", 
2194                         "Channel1: %s\r\n"
2195                         "Channel2: %s\r\n",
2196                         c0->name, c1->name);
2197
2198         for (/* ever */;;) {
2199                 /* Stop if we're a zombie or need a soft hangup */
2200                 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) {
2201                         *fo = NULL;
2202                         if (who) *rc = who;
2203                         res = 0;
2204                         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");
2205                         break;
2206                 }
2207                 if (c0->pvt->bridge && 
2208                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2209                                 /* Looks like they share a bridge code */
2210                         if (option_verbose > 2) 
2211                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2212                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2213                                 c0->bridge = NULL;
2214                                 c1->bridge = NULL;
2215                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2216                                         "Channel1: %s\r\n"
2217                                         "Channel2: %s\r\n",
2218                                         c0->name, c1->name);
2219                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2220                                 return 0;
2221                         }
2222                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2223                            my not wanting to bridge */
2224                         if ((res != -2) && (res != -3))
2225                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2226                         if (res != -3) nativefailed++;
2227                 }
2228         
2229                         
2230                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2231                         !(c0->generator || c1->generator))  {
2232                         if (ast_channel_make_compatible(c0, c1)) {
2233                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2234                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2235                                         "Channel1: %s\r\n"
2236                                         "Channel2: %s\r\n",
2237                                         c0->name, c1->name);
2238                                 return -1;
2239                         }
2240                 }
2241                 who = ast_waitfor_n(cs, 2, &to);
2242                 if (!who) {
2243                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2244                         continue;
2245                 }
2246                 f = ast_read(who);
2247                 if (!f) {
2248                         *fo = NULL;
2249                         *rc = who;
2250                         res = 0;
2251                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2252                         break;
2253                 }
2254
2255                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2256                         *fo = f;
2257                         *rc = who;
2258                         res =  0;
2259                         ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2260                         break;
2261                 }
2262                 if ((f->frametype == AST_FRAME_VOICE) ||
2263                         (f->frametype == AST_FRAME_TEXT) ||
2264                         (f->frametype == AST_FRAME_VIDEO) || 
2265                         (f->frametype == AST_FRAME_IMAGE) ||
2266                         (f->frametype == AST_FRAME_DTMF)) {
2267                         if ((f->frametype == AST_FRAME_DTMF) && 
2268                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2269                                 if ((who == c0)) {
2270                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2271                                                 *rc = c0;
2272                                                 *fo = f;
2273                                                 /* Take out of conference mode */
2274                                                 res = 0;
2275                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2276                                                 break;
2277                                         } else 
2278                                                 goto tackygoto;
2279                                 } else
2280                                 if ((who == c1)) {
2281                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2282                                                 *rc = c1;
2283                                                 *fo = f;
2284                                                 res =  0;
2285                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2286                                                 break;
2287                                         } else
2288                                                 goto tackygoto;
2289                                 }
2290                         } else {
2291 #if 0
2292                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2293                                 if (who == last) 
2294                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2295                                 last = who;
2296 #endif
2297 tackygoto:
2298                                 /* Don't copy packets if there is a generator on either one, since they're
2299                                    not supposed to be listening anyway */
2300                                 if (who == c0) 
2301                                         ast_write(c1, f);
2302                                 else 
2303                                         ast_write(c0, f);
2304                         }
2305                         ast_frfree(f);
2306                 } else
2307                         ast_frfree(f);
2308                 /* Swap who gets priority */
2309                 cs[2] = cs[0];
2310                 cs[0] = cs[1];
2311                 cs[1] = cs[2];
2312         }
2313         c0->bridge = NULL;
2314         c1->bridge = NULL;
2315         manager_event(EVENT_FLAG_CALL, "Unlink", 
2316                                         "Channel1: %s\r\n"
2317                                         "Channel2: %s\r\n",
2318                                         c0->name, c1->name);
2319         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2320         return res;
2321 }
2322
2323 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2324 {
2325         int res;
2326         if (chan->pvt->setoption) {
2327                 res = chan->pvt->setoption(chan, option, data, datalen);
2328                 if (res < 0)
2329                         return res;
2330         } else {
2331                 errno = ENOSYS;
2332                 return -1;
2333         }
2334         if (block) {
2335                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2336                    intermediate packets. XXX */
2337                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2338                 return -1;
2339         }
2340         return 0;
2341 }
2342
2343 struct tonepair_def {
2344         int freq1;
2345         int freq2;
2346         int duration;
2347         int vol;
2348 };
2349
2350 struct tonepair_state {
2351         float freq1;
2352         float freq2;
2353         float vol;
2354         int duration;
2355         int pos;
2356         int origwfmt;
2357         struct ast_frame f;
2358         unsigned char offset[AST_FRIENDLY_OFFSET];
2359         short data[4000];
2360 };
2361
2362 static void tonepair_release(struct ast_channel *chan, void *params)
2363 {
2364         struct tonepair_state *ts = params;
2365         if (chan) {
2366                 ast_set_write_format(chan, ts->origwfmt);
2367         }
2368         free(ts);
2369 }
2370
2371 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2372 {
2373         struct tonepair_state *ts;
2374         struct tonepair_def *td = params;
2375         ts = malloc(sizeof(struct tonepair_state));
2376         if (!ts)
2377                 return NULL;
2378         memset(ts, 0, sizeof(struct tonepair_state));
2379         ts->origwfmt = chan->writeformat;
2380         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2381                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2382                 tonepair_release(NULL, ts);
2383                 ts = NULL;
2384         } else {
2385                 ts->freq1 = td->freq1;
2386                 ts->freq2 = td->freq2;
2387                 ts->duration = td->duration;
2388                 ts->vol = td->vol;
2389         }
2390         /* Let interrupts interrupt :) */
2391         chan->writeinterrupt = 1;
2392         return ts;
2393 }
2394
2395 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2396 {
2397         struct tonepair_state *ts = data;
2398         int x;
2399
2400         /* we need to prepare a frame with 16 * timelen samples as we're 
2401          * generating SLIN audio
2402          */
2403         len = samples * 2;
2404
2405         if (len > sizeof(ts->data) / 2 - 1) {
2406                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2407                 return -1;
2408         }
2409         memset(&ts->f, 0, sizeof(ts->f));
2410         for (x=0;x<len/2;x++) {
2411                 ts->data[x] = ts->vol * (
2412                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2413                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2414                         );
2415         }
2416         ts->f.frametype = AST_FRAME_VOICE;
2417         ts->f.subclass = AST_FORMAT_SLINEAR;
2418         ts->f.datalen = len;
2419         ts->f.samples = samples;
2420         ts->f.offset = AST_FRIENDLY_OFFSET;
2421         ts->f.data = ts->data;
2422         ast_write(chan, &ts->f);
2423         ts->pos += x;
2424         if (ts->duration > 0) {
2425                 if (ts->pos >= ts->duration * 8)
2426                         return -1;
2427         }
2428         return 0;
2429 }
2430
2431 static struct ast_generator tonepair = {
2432         alloc: tonepair_alloc,
2433         release: tonepair_release,
2434         generate: tonepair_generator,
2435 };
2436
2437 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2438 {
2439         struct tonepair_def d = { 0, };
2440         d.freq1 = freq1;
2441         d.freq2 = freq2;
2442         d.duration = duration;
2443         if (vol < 1)
2444                 d.vol = 8192;
2445         else
2446                 d.vol = vol;
2447         if (ast_activate_generator(chan, &tonepair, &d))
2448                 return -1;
2449         return 0;
2450 }
2451
2452 void ast_tonepair_stop(struct ast_channel *chan)
2453 {
2454         ast_deactivate_generator(chan);
2455 }
2456
2457 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2458 {
2459         struct ast_frame *f;
2460         int res;
2461         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2462                 return res;
2463
2464         /* Give us some wiggle room */
2465         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2466                 f = ast_read(chan);
2467                 if (f)
2468                         ast_frfree(f);
2469                 else
2470                         return -1;
2471         }
2472         return 0;
2473 }
2474