00c863b75a78c3d9633aae1fdf7e3fc9a82d41cd
[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                 res = do_senddigit(chan,fr->subclass);
1367                 break;
1368         case AST_FRAME_TEXT:
1369                 if (chan->pvt->send_text)
1370                         res = chan->pvt->send_text(chan, (char *) fr->data);
1371                 break;
1372         case AST_FRAME_VIDEO:
1373                 /* XXX Handle translation of video codecs one day XXX */
1374                 if (chan->pvt->write_video)
1375                         res = chan->pvt->write_video(chan, fr);
1376                 else
1377                         res = 0;
1378                 break;
1379         default:
1380                 if (chan->pvt->write) {
1381                         if (chan->pvt->writetrans) {
1382                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1383                         } else
1384                                 f = fr;
1385                         if (f) {
1386                                 res = chan->pvt->write(chan, f);
1387                                 if( chan->monitor &&
1388                                                 chan->monitor->write_stream &&
1389                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1390 #ifndef MONITOR_CONSTANT_DELAY
1391                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1392                                         if (jump >= 0) {
1393                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1394                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1395                                                 chan->outsmpl += jump + 2 * f->samples;
1396                                         } else
1397                                                 chan->outsmpl += f->samples;
1398 #else
1399                                         int jump = chan->insmpl - chan->outsmpl;
1400                                         if (jump - MONITOR_DELAY >= 0) {
1401                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1402                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1403                                                 chan->outsmpl += jump;
1404                                         } else
1405                                                 chan->outsmpl += f->samples;
1406 #endif
1407                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1408                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1409                                 }
1410                         } else
1411                                 res = 0;
1412                 }
1413         }
1414         if (f && (f != fr))
1415                 ast_frfree(f);
1416         chan->blocking = 0;
1417         /* Consider a write failure to force a soft hangup */
1418         if (res < 0)
1419                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1420         else {
1421                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1422                         chan->fout &= 0x80000000;
1423                 else
1424                         chan->fout++;
1425                 chan->fout++;
1426         }
1427         ast_mutex_unlock(&chan->lock);
1428         return res;
1429 }
1430
1431 int ast_set_write_format(struct ast_channel *chan, int fmts)
1432 {
1433         int fmt;
1434         int native;
1435         int res;
1436         
1437         native = chan->nativeformats;
1438         fmt = fmts;
1439         
1440         res = ast_translator_best_choice(&native, &fmt);
1441         if (res < 0) {
1442                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1443                         ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1444                 return -1;
1445         }
1446         
1447         /* Now we have a good choice for both.  We'll write using our native format. */
1448         chan->pvt->rawwriteformat = native;
1449         /* User perspective is fmt */
1450         chan->writeformat = fmt;
1451         /* Free any write translation we have right now */
1452         if (chan->pvt->writetrans)
1453                 ast_translator_free_path(chan->pvt->writetrans);
1454         /* Build a translation path from the user write format to the raw writing format */
1455         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1456         if (option_debug)
1457                 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1458         return 0;
1459 }
1460
1461 int ast_set_read_format(struct ast_channel *chan, int fmts)
1462 {
1463         int fmt;
1464         int native;
1465         int res;
1466         
1467         native = chan->nativeformats;
1468         fmt = fmts;
1469         /* Find a translation path from the native read format to one of the user's read formats */
1470         res = ast_translator_best_choice(&fmt, &native);
1471         if (res < 0) {
1472                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1473                         ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1474                 return -1;
1475         }
1476         
1477         /* Now we have a good choice for both.  We'll write using our native format. */
1478         chan->pvt->rawreadformat = native;
1479         /* User perspective is fmt */
1480         chan->readformat = fmt;
1481         /* Free any read translation we have right now */
1482         if (chan->pvt->readtrans)
1483                 ast_translator_free_path(chan->pvt->readtrans);
1484         /* Build a translation path from the raw read format to the user reading format */
1485         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1486         if (option_debug)
1487                 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n", 
1488                         chan->name, ast_getformatname(chan->readformat));
1489         return 0;
1490 }
1491
1492 struct ast_channel *__ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid, struct outgoing_helper *oh)
1493 {
1494         int state = 0;
1495         struct ast_channel *chan;
1496         struct ast_frame *f;
1497         int res = 0;
1498         chan = ast_request(type, format, data);
1499         if (chan) {
1500                 if (oh) {
1501                         char *tmp, *var;
1502                         /* JDG chanvar */
1503                         tmp = oh->variable;
1504                         /* FIXME replace this call with strsep  NOT*/
1505                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1506                                 pbx_builtin_setvar( chan, var );
1507                         } /* /JDG */
1508                         if (*oh->context)
1509                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1510                         if (*oh->exten)
1511                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1512                         if (*oh->callerid)
1513                                 ast_set_callerid(chan, oh->callerid, 1);
1514                         chan->priority = oh->priority;
1515                 }
1516
1517                 if (!ast_call(chan, data, 0)) {
1518                         while(timeout && (chan->_state != AST_STATE_UP)) {
1519                                 res = ast_waitfor(chan, timeout);
1520                                 if (res < 0) {
1521                                         /* Something not cool, or timed out */
1522                                         break;
1523                                 }
1524                                 /* If done, break out */
1525                                 if (!res)
1526                                         break;
1527                                 if (timeout > -1)
1528                                         timeout = res;
1529                                 f = ast_read(chan);
1530                                 if (!f) {
1531                                         state = AST_CONTROL_HANGUP;
1532                                         res = 0;
1533                                         break;
1534                                 }
1535                                 if (f->frametype == AST_FRAME_CONTROL) {
1536                                         if (f->subclass == AST_CONTROL_RINGING)
1537                                                 state = AST_CONTROL_RINGING;
1538                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1539                                                 state = f->subclass;
1540                                                 ast_frfree(f);
1541                                                 break;
1542                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1543                                                 state = f->subclass;
1544                                                 ast_frfree(f);
1545                                                 break;
1546                                         } else {
1547                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1548                                         }
1549                                 }
1550                                 ast_frfree(f);
1551                         }
1552                 } else
1553                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1554         } else
1555                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1556         if (chan && (chan->_state == AST_STATE_UP))
1557                 state = AST_CONTROL_ANSWER;
1558         if (outstate)
1559                 *outstate = state;
1560         if (chan && res <= 0) {
1561                 if (!chan->cdr) {
1562                         chan->cdr = ast_cdr_alloc();
1563                         if (chan->cdr)
1564                                 ast_cdr_init(chan->cdr, chan);
1565                 }
1566                 if (chan->cdr) {
1567                         char tmp[256];
1568                         sprintf(tmp, "%s/%s",type,(char *)data);
1569                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1570                         ast_cdr_update(chan);
1571                         ast_cdr_start(chan->cdr);
1572                         ast_cdr_end(chan->cdr);
1573                         /* If the cause wasn't handled properly */
1574                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1575                                 ast_cdr_failed(chan->cdr);
1576                 } else 
1577                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1578                 ast_hangup(chan);
1579                 chan = NULL;
1580         }
1581         return chan;
1582 }
1583
1584 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1585 {
1586         return __ast_request_and_dial(type, format, data, timeout, outstate, callerid, NULL);
1587 }
1588
1589 struct ast_channel *ast_request(char *type, int format, void *data)
1590 {
1591         struct chanlist *chan;
1592         struct ast_channel *c = NULL;
1593         int capabilities;
1594         int fmt;
1595         int res;
1596         if (ast_mutex_lock(&chlock)) {
1597                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1598                 return NULL;
1599         }
1600         chan = backends;
1601         while(chan) {
1602                 if (!strcasecmp(type, chan->type)) {
1603                         capabilities = chan->capabilities;
1604                         fmt = format;
1605                         res = ast_translator_best_choice(&fmt, &capabilities);
1606                         if (res < 0) {
1607                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1608                                 ast_mutex_unlock(&chlock);
1609                                 return NULL;
1610                         }
1611                         ast_mutex_unlock(&chlock);
1612                         if (chan->requester)
1613                                 c = chan->requester(type, capabilities, data);
1614                         if (c) {
1615                                 if (c->_state == AST_STATE_DOWN) {
1616                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1617                                         "Channel: %s\r\n"
1618                                         "State: %s\r\n"
1619                                         "Callerid: %s\r\n"
1620                                         "Uniqueid: %s\r\n",
1621                                         c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1622                                 }
1623                         }
1624                         return c;
1625                 }
1626                 chan = chan->next;
1627         }
1628         if (!chan)
1629                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1630         ast_mutex_unlock(&chlock);
1631         return c;
1632 }
1633
1634 int ast_parse_device_state(char *device)
1635 {
1636         char name[AST_CHANNEL_NAME] = "";
1637         char *cut;
1638         struct ast_channel *chan;
1639
1640         chan = ast_channel_walk(NULL);
1641         while (chan) {
1642                 strncpy(name, chan->name, sizeof(name)-1);
1643                 cut = strchr(name,'-');
1644                 if (cut)
1645                         *cut = 0;
1646                 if (!strcmp(name, device))
1647                         return AST_DEVICE_INUSE;
1648                 chan = ast_channel_walk(chan);
1649         }
1650         return AST_DEVICE_UNKNOWN;
1651 }
1652
1653 int ast_device_state(char *device)
1654 {
1655         char tech[AST_MAX_EXTENSION] = "";
1656         char *number;
1657         struct chanlist *chanls;
1658         int res = 0;
1659         
1660         strncpy(tech, device, sizeof(tech)-1);
1661         number = strchr(tech, '/');
1662         if (!number) {
1663             return AST_DEVICE_INVALID;
1664         }
1665         *number = 0;
1666         number++;
1667                 
1668         if (ast_mutex_lock(&chlock)) {
1669                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1670                 return -1;
1671         }
1672         chanls = backends;
1673         while(chanls) {
1674                 if (!strcasecmp(tech, chanls->type)) {
1675                         ast_mutex_unlock(&chlock);
1676                         if (!chanls->devicestate) 
1677                                 return ast_parse_device_state(device);
1678                         else {
1679                                 res = chanls->devicestate(number);
1680                                 if (res == AST_DEVICE_UNKNOWN)
1681                                         return ast_parse_device_state(device);
1682                                 else
1683                                         return res;
1684                         }
1685                 }
1686                 chanls = chanls->next;
1687         }
1688         ast_mutex_unlock(&chlock);
1689         return AST_DEVICE_INVALID;
1690 }
1691
1692 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1693 {
1694         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1695            If the remote end does not answer within the timeout, then do NOT hang up, but 
1696            return anyway.  */
1697         int res = -1;
1698         /* Stop if we're a zombie or need a soft hangup */
1699         ast_mutex_lock(&chan->lock);
1700         if (!chan->zombie && !ast_check_hangup(chan)) 
1701                 if (chan->pvt->call)
1702                         res = chan->pvt->call(chan, addr, timeout);
1703         ast_mutex_unlock(&chan->lock);
1704         return res;
1705 }
1706
1707 int ast_transfer(struct ast_channel *chan, char *dest) 
1708 {
1709         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1710            If the remote end does not answer within the timeout, then do NOT hang up, but 
1711            return anyway.  */
1712         int res = -1;
1713         /* Stop if we're a zombie or need a soft hangup */
1714         ast_mutex_lock(&chan->lock);
1715         if (!chan->zombie && !ast_check_hangup(chan)) {
1716                 if (chan->pvt->transfer) {
1717                         res = chan->pvt->transfer(chan, dest);
1718                         if (!res)
1719                                 res = 1;
1720                 } else
1721                         res = 0;
1722         }
1723         ast_mutex_unlock(&chan->lock);
1724         return res;
1725 }
1726
1727 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1728 {
1729         int pos=0;
1730         int to = ftimeout;
1731         char d;
1732         /* XXX Merge with full version? XXX */
1733         /* Stop if we're a zombie or need a soft hangup */
1734         if (c->zombie || ast_check_hangup(c)) 
1735                 return -1;
1736         if (!len)
1737                 return -1;
1738         do {
1739                 if (c->stream) {
1740                         d = ast_waitstream(c, AST_DIGIT_ANY);
1741                         ast_stopstream(c);
1742                         usleep(1000);
1743                         if (!d)
1744                                 d = ast_waitfordigit(c, to);
1745                 } else {
1746                         d = ast_waitfordigit(c, to);
1747                 }
1748                 if (d < 0)
1749                         return -1;
1750                 if (d == 0) {
1751                         s[pos]='\0';
1752                         return 1;
1753                 }
1754                 if (!strchr(enders, d))
1755                         s[pos++] = d;
1756                 if (strchr(enders, d) || (pos >= len)) {
1757                         s[pos]='\0';
1758                         return 0;
1759                 }
1760                 to = timeout;
1761         } while(1);
1762         /* Never reached */
1763         return 0;
1764 }
1765
1766 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1767 {
1768         int pos=0;
1769         int to = ftimeout;
1770         char d;
1771         /* Stop if we're a zombie or need a soft hangup */
1772         if (c->zombie || ast_check_hangup(c)) 
1773                 return -1;
1774         if (!len)
1775                 return -1;
1776         do {
1777                 if (c->stream) {
1778                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1779                         ast_stopstream(c);
1780                         usleep(1000);
1781                         if (!d)
1782                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1783                 } else {
1784                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1785                 }
1786                 if (d < 0)
1787                         return -1;
1788                 if (d == 0) {
1789                         s[pos]='\0';
1790                         return 1;
1791                 }
1792                 if (d == 1) {
1793                         s[pos]='\0';
1794                         return 2;
1795                 }
1796                 if (!strchr(enders, d))
1797                         s[pos++] = d;
1798                 if (strchr(enders, d) || (pos >= len)) {
1799                         s[pos]='\0';
1800                         return 0;
1801                 }
1802                 to = timeout;
1803         } while(1);
1804         /* Never reached */
1805         return 0;
1806 }
1807
1808 int ast_channel_supports_html(struct ast_channel *chan)
1809 {
1810         if (chan->pvt->send_html)
1811                 return 1;
1812         return 0;
1813 }
1814
1815 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1816 {
1817         if (chan->pvt->send_html)
1818                 return chan->pvt->send_html(chan, subclass, data, datalen);
1819         return -1;
1820 }
1821
1822 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1823 {
1824         if (chan->pvt->send_html)
1825                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1826         return -1;
1827 }
1828
1829 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1830 {
1831         int peerf;
1832         int chanf;
1833         int res;
1834         peerf = peer->nativeformats;
1835         chanf = chan->nativeformats;
1836         res = ast_translator_best_choice(&peerf, &chanf);
1837         if (res < 0) {
1838                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1839                 return -1;
1840         }
1841         /* Set read format on channel */
1842         res = ast_set_read_format(chan, peerf);
1843         if (res < 0) {
1844                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1845                 return -1;
1846         }
1847         /* Set write format on peer channel */
1848         res = ast_set_write_format(peer, peerf);
1849         if (res < 0) {
1850                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1851                 return -1;
1852         }
1853         /* Now we go the other way */
1854         peerf = peer->nativeformats;
1855         chanf = chan->nativeformats;
1856         res = ast_translator_best_choice(&chanf, &peerf);
1857         if (res < 0) {
1858                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1859                 return -1;
1860         }
1861         /* Set writeformat on channel */
1862         res = ast_set_write_format(chan, chanf);
1863         if (res < 0) {
1864                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1865                 return -1;
1866         }
1867         /* Set read format on peer channel */
1868         res = ast_set_read_format(peer, chanf);
1869         if (res < 0) {
1870                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1871                 return -1;
1872         }
1873         return 0;
1874 }
1875
1876 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1877 {
1878         struct ast_frame null = { AST_FRAME_NULL, };
1879         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1880                 clone->name, original->name);
1881         if (original->masq) {
1882                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1883                         original->masq->name, original->name);
1884                 return -1;
1885         }
1886         if (clone->masqr) {
1887                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1888                         clone->name, clone->masqr->name);
1889                 return -1;
1890         }
1891         original->masq = clone;
1892         clone->masqr = original;
1893         /* XXX can't really hold the lock here, but at the same time, it' s
1894            not really safe not to XXX */
1895         ast_queue_frame(original, &null, 0);
1896         ast_queue_frame(clone, &null, 0);
1897         ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1898         return 0;
1899 }
1900
1901 void ast_change_name(struct ast_channel *chan, char *newname)
1902 {
1903         char tmp[256];
1904         strncpy(tmp, chan->name, 256);
1905         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1906         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
1907 }
1908
1909 static int ast_do_masquerade(struct ast_channel *original)
1910 {
1911         int x,i;
1912         int res=0;
1913         char *tmp;
1914         void *tmpv;
1915         struct ast_frame *cur, *prev;
1916         struct ast_channel_pvt *p;
1917         struct ast_channel *clone = original->masq;
1918         int rformat = original->readformat;
1919         int wformat = original->writeformat;
1920         char newn[100];
1921         char orig[100];
1922         char masqn[100];
1923         char zombn[100];
1924         
1925 #if 1
1926         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1927                 clone->name, clone->_state, original->name, original->_state);
1928 #endif
1929         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1930            the clone channel into the original channel.  Start by killing off the original
1931            channel's backend.   I'm not sure we're going to keep this function, because 
1932            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1933
1934         /* We need the clone's lock, too */
1935         ast_mutex_lock(&clone->lock);
1936
1937         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
1938
1939         /* Having remembered the original read/write formats, we turn off any translation on either
1940            one */
1941         free_translation(clone);
1942         free_translation(original);
1943
1944
1945         /* Unlink the masquerade */
1946         original->masq = NULL;
1947         clone->masqr = NULL;
1948         
1949         /* Save the original name */
1950         strncpy(orig, original->name, sizeof(orig) - 1);
1951         /* Save the new name */
1952         strncpy(newn, clone->name, sizeof(newn) - 1);
1953         /* Create the masq name */
1954         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1955                 
1956         /* Copy the name from the clone channel */
1957         strncpy(original->name, newn, sizeof(original->name)-1);
1958
1959         /* Mangle the name of the clone channel */
1960         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1961         
1962         /* Notify any managers of the change, first the masq then the other */
1963         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1964         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1965
1966         /* Swap the guts */     
1967         p = original->pvt;
1968         original->pvt = clone->pvt;
1969         clone->pvt = p;
1970
1971         /* Save any pending frames on both sides.  Start by counting
1972          * how many we're going to need... */
1973         prev = NULL;
1974         cur = clone->pvt->readq;
1975         x = 0;
1976         while(cur) {
1977                 x++;
1978                 prev = cur;
1979                 cur = cur->next;
1980         }
1981         /* If we had any, prepend them to the ones already in the queue, and 
1982          * load up the alertpipe */
1983         if (prev) {
1984                 prev->next = original->pvt->readq;
1985                 original->pvt->readq = clone->pvt->readq;
1986                 clone->pvt->readq = NULL;
1987                 if (original->pvt->alertpipe[1] > -1) {
1988                         for (i=0;i<x;i++)
1989                                 write(original->pvt->alertpipe[1], &x, sizeof(x));
1990                 }
1991         }
1992         clone->_softhangup = AST_SOFTHANGUP_DEV;
1993
1994
1995         if (clone->pvt->fixup){
1996                 res = clone->pvt->fixup(original, clone);
1997                 if (res) 
1998                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1999         }
2000
2001         /* Start by disconnecting the original's physical side */
2002         if (clone->pvt->hangup)
2003                 res = clone->pvt->hangup(clone);
2004         if (res) {
2005                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2006                 ast_mutex_unlock(&clone->lock);
2007                 return -1;
2008         }
2009         
2010         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2011         /* Mangle the name of the clone channel */
2012         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2013         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
2014
2015         /* Keep the same language.  */
2016         /* Update the type. */
2017         original->type = clone->type;
2018         /* Copy the FD's */
2019         for (x=0;x<AST_MAX_FDS;x++) {
2020                 original->fds[x] = clone->fds[x];
2021         }
2022         /* Move the variables */
2023         tmpv = original->varshead.first;
2024         original->varshead.first = clone->varshead.first;
2025         clone->varshead.first = tmpv;
2026         /* Presense of ADSI capable CPE follows clone */
2027         original->adsicpe = clone->adsicpe;
2028         /* Bridge remains the same */
2029         /* CDR fields remain the same */
2030         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2031         /* Application and data remain the same */
2032         /* Clone exception  becomes real one, as with fdno */
2033         original->exception = clone->exception;
2034         original->fdno = clone->fdno;
2035         /* Schedule context remains the same */
2036         /* Stream stuff stays the same */
2037         /* Keep the original state.  The fixup code will need to work with it most likely */
2038
2039         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
2040            fields back into the defunct 'clone' so that they will be freed when
2041            ast_frfree is eventually called */
2042         tmp = original->dnid;
2043         original->dnid = clone->dnid;
2044         clone->dnid = tmp;
2045         
2046         tmp = original->callerid;
2047         original->callerid = clone->callerid;
2048         clone->callerid = tmp;
2049         
2050         /* Restore original timing file descriptor */
2051         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2052         
2053         /* Our native formats are different now */
2054         original->nativeformats = clone->nativeformats;
2055
2056         /* And of course, so does our current state.  Note we need not
2057            call ast_setstate since the event manager doesn't really consider
2058            these separate */
2059         original->_state = clone->_state;
2060         
2061         /* Context, extension, priority, app data, jump table,  remain the same */
2062         /* pvt switches.  pbx stays the same, as does next */
2063         
2064         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2065            a zombie so nothing tries to touch it.  If it's already been marked as a
2066            zombie, then free it now (since it already is considered invalid). */
2067         if (clone->zombie) {
2068                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2069                 ast_mutex_unlock(&clone->lock);
2070                 ast_channel_free(clone);
2071                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2072         } else {
2073                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2074                 clone->zombie=1;
2075                 ast_mutex_unlock(&clone->lock);
2076         }
2077         /* Set the write format */
2078         ast_set_write_format(original, wformat);
2079
2080         /* Set the read format */
2081         ast_set_read_format(original, rformat);
2082
2083         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2084
2085         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2086            can fix up everything as best as possible */
2087         if (original->pvt->fixup) {
2088                 res = original->pvt->fixup(clone, original);
2089                 if (res) {
2090                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2091                                 original->type, original->name);
2092                         return -1;
2093                 }
2094         } else
2095                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2096                         original->type, original->name);
2097         /* Signal any blocker */
2098         if (original->blocking)
2099                 pthread_kill(original->blocker, SIGURG);
2100         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2101                 original->name, original->_state);
2102         return 0;
2103 }
2104
2105 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2106 {
2107         if (chan->callerid)
2108                 free(chan->callerid);
2109         if (anitoo && chan->ani)
2110                 free(chan->ani);
2111         if (callerid) {
2112                 chan->callerid = strdup(callerid);
2113                 if (anitoo)
2114                         chan->ani = strdup(callerid);
2115         } else {
2116                 chan->callerid = NULL;
2117                 if (anitoo)
2118                         chan->ani = NULL;
2119         }
2120         if (chan->cdr)
2121                 ast_cdr_setcid(chan->cdr, chan);
2122         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2123                                 "Channel: %s\r\n"
2124                                 "Callerid: %s\r\n"
2125                                 "Uniqueid: %s\r\n",
2126                                 chan->name, chan->callerid ? 
2127                                 chan->callerid : "<Unknown>",
2128                                 chan->uniqueid);
2129 }
2130
2131 int ast_setstate(struct ast_channel *chan, int state)
2132 {
2133         if (chan->_state != state) {
2134                 int oldstate = chan->_state;
2135                 chan->_state = state;
2136                 if (oldstate == AST_STATE_DOWN) {
2137                         ast_device_state_changed(chan->name);
2138                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2139                         "Channel: %s\r\n"
2140                         "State: %s\r\n"
2141                         "Callerid: %s\r\n"
2142                         "Uniqueid: %s\r\n",
2143                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2144                 } else {
2145                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2146                                 "Channel: %s\r\n"
2147                                 "State: %s\r\n"
2148                                 "Callerid: %s\r\n"
2149                                 "Uniqueid: %s\r\n",
2150                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2151                 }
2152         }
2153         return 0;
2154 }
2155
2156 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2157 {
2158         /* Copy voice back and forth between the two channels.  Give the peer
2159            the ability to transfer calls with '#<extension' syntax. */
2160         struct ast_channel *cs[3];
2161         int to = -1;
2162         struct ast_frame *f;
2163         struct ast_channel *who = NULL;
2164         int res;
2165         int nativefailed=0;
2166
2167         /* Stop if we're a zombie or need a soft hangup */
2168         if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) 
2169                 return -1;
2170         if (c0->bridge) {
2171                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2172                         c0->name, c0->bridge->name);
2173                 return -1;
2174         }
2175         if (c1->bridge) {
2176                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2177                         c1->name, c1->bridge->name);
2178                 return -1;
2179         }
2180         
2181         /* Keep track of bridge */
2182         c0->bridge = c1;
2183         c1->bridge = c0;
2184         cs[0] = c0;
2185         cs[1] = c1;
2186         
2187         manager_event(EVENT_FLAG_CALL, "Link", 
2188                         "Channel1: %s\r\n"
2189                         "Channel2: %s\r\n",
2190                         c0->name, c1->name);
2191
2192         for (/* ever */;;) {
2193                 /* Stop if we're a zombie or need a soft hangup */
2194                 if (c0->zombie || ast_check_hangup_locked(c0) || c1->zombie || ast_check_hangup_locked(c1)) {
2195                         *fo = NULL;
2196                         if (who) *rc = who;
2197                         res = 0;
2198                         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");
2199                         break;
2200                 }
2201                 if (c0->pvt->bridge && 
2202                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2203                                 /* Looks like they share a bridge code */
2204                         if (option_verbose > 2) 
2205                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2206                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2207                                 c0->bridge = NULL;
2208                                 c1->bridge = NULL;
2209                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2210                                         "Channel1: %s\r\n"
2211                                         "Channel2: %s\r\n",
2212                                         c0->name, c1->name);
2213                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2214                                 return 0;
2215                         }
2216                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2217                            my not wanting to bridge */
2218                         if ((res != -2) && (res != -3))
2219                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2220                         if (res != -3) nativefailed++;
2221                 }
2222         
2223                         
2224                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2225                         !(c0->generator || c1->generator))  {
2226                         if (ast_channel_make_compatible(c0, c1)) {
2227                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2228                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2229                                         "Channel1: %s\r\n"
2230                                         "Channel2: %s\r\n",
2231                                         c0->name, c1->name);
2232                                 return -1;
2233                         }
2234                 }
2235                 who = ast_waitfor_n(cs, 2, &to);
2236                 if (!who) {
2237                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2238                         continue;
2239                 }
2240                 f = ast_read(who);
2241                 if (!f) {
2242                         *fo = NULL;
2243                         *rc = who;
2244                         res = 0;
2245                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2246                         break;
2247                 }
2248
2249                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2250                         *fo = f;
2251                         *rc = who;
2252                         res =  0;
2253                         ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2254                         break;
2255                 }
2256                 if ((f->frametype == AST_FRAME_VOICE) ||
2257                         (f->frametype == AST_FRAME_TEXT) ||
2258                         (f->frametype == AST_FRAME_VIDEO) || 
2259                         (f->frametype == AST_FRAME_IMAGE) ||
2260                         (f->frametype == AST_FRAME_DTMF)) {
2261                         if ((f->frametype == AST_FRAME_DTMF) && 
2262                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2263                                 if ((who == c0)) {
2264                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2265                                                 *rc = c0;
2266                                                 *fo = f;
2267                                                 /* Take out of conference mode */
2268                                                 res = 0;
2269                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2270                                                 break;
2271                                         } else 
2272                                                 goto tackygoto;
2273                                 } else
2274                                 if ((who == c1)) {
2275                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2276                                                 *rc = c1;
2277                                                 *fo = f;
2278                                                 res =  0;
2279                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2280                                                 break;
2281                                         } else
2282                                                 goto tackygoto;
2283                                 }
2284                         } else {
2285 #if 0
2286                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2287                                 if (who == last) 
2288                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2289                                 last = who;
2290 #endif
2291 tackygoto:
2292                                 /* Don't copy packets if there is a generator on either one, since they're
2293                                    not supposed to be listening anyway */
2294                                 if (who == c0) 
2295                                         ast_write(c1, f);
2296                                 else 
2297                                         ast_write(c0, f);
2298                         }
2299                         ast_frfree(f);
2300                 } else
2301                         ast_frfree(f);
2302                 /* Swap who gets priority */
2303                 cs[2] = cs[0];
2304                 cs[0] = cs[1];
2305                 cs[1] = cs[2];
2306         }
2307         c0->bridge = NULL;
2308         c1->bridge = NULL;
2309         manager_event(EVENT_FLAG_CALL, "Unlink", 
2310                                         "Channel1: %s\r\n"
2311                                         "Channel2: %s\r\n",
2312                                         c0->name, c1->name);
2313         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2314         return res;
2315 }
2316
2317 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2318 {
2319         int res;
2320         if (chan->pvt->setoption) {
2321                 res = chan->pvt->setoption(chan, option, data, datalen);
2322                 if (res < 0)
2323                         return res;
2324         } else {
2325                 errno = ENOSYS;
2326                 return -1;
2327         }
2328         if (block) {
2329                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2330                    intermediate packets. XXX */
2331                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2332                 return -1;
2333         }
2334         return 0;
2335 }
2336
2337 struct tonepair_def {
2338         int freq1;
2339         int freq2;
2340         int duration;
2341         int vol;
2342 };
2343
2344 struct tonepair_state {
2345         float freq1;
2346         float freq2;
2347         float vol;
2348         int duration;
2349         int pos;
2350         int origwfmt;
2351         struct ast_frame f;
2352         unsigned char offset[AST_FRIENDLY_OFFSET];
2353         short data[4000];
2354 };
2355
2356 static void tonepair_release(struct ast_channel *chan, void *params)
2357 {
2358         struct tonepair_state *ts = params;
2359         if (chan) {
2360                 ast_set_write_format(chan, ts->origwfmt);
2361         }
2362         free(ts);
2363 }
2364
2365 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2366 {
2367         struct tonepair_state *ts;
2368         struct tonepair_def *td = params;
2369         ts = malloc(sizeof(struct tonepair_state));
2370         if (!ts)
2371                 return NULL;
2372         memset(ts, 0, sizeof(struct tonepair_state));
2373         ts->origwfmt = chan->writeformat;
2374         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2375                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2376                 tonepair_release(NULL, ts);
2377                 ts = NULL;
2378         } else {
2379                 ts->freq1 = td->freq1;
2380                 ts->freq2 = td->freq2;
2381                 ts->duration = td->duration;
2382                 ts->vol = td->vol;
2383         }
2384         /* Let interrupts interrupt :) */
2385         chan->writeinterrupt = 1;
2386         return ts;
2387 }
2388
2389 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2390 {
2391         struct tonepair_state *ts = data;
2392         int x;
2393
2394         /* we need to prepare a frame with 16 * timelen samples as we're 
2395          * generating SLIN audio
2396          */
2397         len = samples * 2;
2398
2399         if (len > sizeof(ts->data) / 2 - 1) {
2400                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2401                 return -1;
2402         }
2403         memset(&ts->f, 0, sizeof(ts->f));
2404         for (x=0;x<len/2;x++) {
2405                 ts->data[x] = ts->vol * (
2406                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2407                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2408                         );
2409         }
2410         ts->f.frametype = AST_FRAME_VOICE;
2411         ts->f.subclass = AST_FORMAT_SLINEAR;
2412         ts->f.datalen = len;
2413         ts->f.samples = samples;
2414         ts->f.offset = AST_FRIENDLY_OFFSET;
2415         ts->f.data = ts->data;
2416         ast_write(chan, &ts->f);
2417         ts->pos += x;
2418         if (ts->duration > 0) {
2419                 if (ts->pos >= ts->duration * 8)
2420                         return -1;
2421         }
2422         return 0;
2423 }
2424
2425 static struct ast_generator tonepair = {
2426         alloc: tonepair_alloc,
2427         release: tonepair_release,
2428         generate: tonepair_generator,
2429 };
2430
2431 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2432 {
2433         struct tonepair_def d = { 0, };
2434         d.freq1 = freq1;
2435         d.freq2 = freq2;
2436         d.duration = duration;
2437         if (vol < 1)
2438                 d.vol = 8192;
2439         else
2440                 d.vol = vol;
2441         if (ast_activate_generator(chan, &tonepair, &d))
2442                 return -1;
2443         return 0;
2444 }
2445
2446 void ast_tonepair_stop(struct ast_channel *chan)
2447 {
2448         ast_deactivate_generator(chan);
2449 }
2450
2451 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2452 {
2453         struct ast_frame *f;
2454         int res;
2455         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2456                 return res;
2457
2458         /* Give us some wiggle room */
2459         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2460                 f = ast_read(chan);
2461                 if (f)
2462                         ast_frfree(f);
2463                 else
2464                         return -1;
2465         }
2466         return 0;
2467 }
2468