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