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