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