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