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