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