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