fd684d48985002a66f44e356d2a75e4e2f3c2295
[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                         } else if (condition == AST_CONTROL_PROGRESS) {
1152                                 /* ast_playtones_stop(chan); */
1153                         } else {
1154                                 /* not handled */
1155                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1156                                 return -1;
1157                         }
1158                 }
1159                 else ast_playtones_stop(chan);
1160         }
1161         return 0;
1162 }
1163
1164 int ast_recvchar(struct ast_channel *chan, int timeout)
1165 {
1166         int res,ourto,c;
1167         struct ast_frame *f;
1168         
1169         ourto = timeout;
1170         for(;;)
1171            {
1172                 if (ast_check_hangup(chan)) return -1;
1173                 res = ast_waitfor(chan,ourto);
1174                 if (res <= 0) /* if timeout */
1175                    {
1176                         return 0;
1177                    }
1178                 ourto = res;
1179                 f = ast_read(chan);
1180                 if (f == NULL) return -1; /* if hangup */
1181                 if ((f->frametype == AST_FRAME_CONTROL) &&
1182                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1183                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1184                    {
1185                         c = *((char *)f->data);  /* get the data */
1186                         ast_frfree(f);
1187                         return(c);
1188                    }
1189                 ast_frfree(f);
1190         }
1191 }
1192
1193 int ast_sendtext(struct ast_channel *chan, char *text)
1194 {
1195         int res = 0;
1196         /* Stop if we're a zombie or need a soft hangup */
1197         if (chan->zombie || ast_check_hangup(chan)) 
1198                 return -1;
1199         CHECK_BLOCKING(chan);
1200         if (chan->pvt->send_text)
1201                 res = chan->pvt->send_text(chan, text);
1202         chan->blocking = 0;
1203         return res;
1204 }
1205
1206 static int do_senddigit(struct ast_channel *chan, char digit)
1207 {
1208         int res = -1;
1209
1210         if (chan->pvt->send_digit)
1211                 res = chan->pvt->send_digit(chan, digit);
1212         if (!chan->pvt->send_digit || res) {
1213                 /*
1214                  * Device does not support DTMF tones, lets fake
1215                  * it by doing our own generation. (PM2002)
1216                  */
1217                 static const char* dtmf_tones[] = {
1218                         "!941+1336/50,!0/50",   /* 0 */
1219                         "!697+1209/50,!0/50",   /* 1 */
1220                         "!697+1336/50,!0/50",   /* 2 */
1221                         "!697+1477/50,!0/50",   /* 3 */
1222                         "!770+1209/50,!0/50",   /* 4 */
1223                         "!770+1336/50,!0/50",   /* 5 */
1224                         "!770+1477/50,!0/50",   /* 6 */
1225                         "!852+1209/50,!0/50",   /* 7 */
1226                         "!852+1336/50,!0/50",   /* 8 */
1227                         "!852+1477/50,!0/50",   /* 9 */
1228                         "!697+1633/50,!0/50",   /* A */
1229                         "!770+1633/50,!0/50",   /* B */
1230                         "!852+1633/50,!0/50",   /* C */
1231                         "!941+1633/50,!0/50",   /* D */
1232                         "!941+1209/50,!0/50",   /* * */
1233                         "!941+1477/50,!0/50" }; /* # */
1234                 if (digit >= '0' && digit <='9')
1235                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1236                 else if (digit >= 'A' && digit <= 'D')
1237                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1238                 else if (digit == '*')
1239                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1240                 else if (digit == '#')
1241                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1242                 else {
1243                         /* not handled */
1244                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1245                         return -1;
1246                 }
1247         }
1248         return 0;
1249 }
1250
1251 int ast_prod(struct ast_channel *chan)
1252 {
1253         struct ast_frame a = { AST_FRAME_VOICE };
1254         char nothing[128];
1255         /* Send an empty audio frame to get things moving */
1256         if (chan->_state != AST_STATE_UP) {
1257                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1258                 a.subclass = chan->pvt->rawwriteformat;
1259                 a.data = nothing + AST_FRIENDLY_OFFSET;
1260                 if (ast_write(chan, &a))
1261                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1262         }
1263         return 0;
1264 }
1265
1266 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1267 {
1268         int res = -1;
1269         struct ast_frame *f = NULL;
1270         /* Stop if we're a zombie or need a soft hangup */
1271         if (chan->zombie || ast_check_hangup(chan)) 
1272                 return -1;
1273         /* Handle any pending masquerades */
1274         if (chan->masq) {
1275                 if (ast_do_masquerade(chan)) {
1276                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1277                         return -1;
1278                 }
1279         }
1280         if (chan->masqr)
1281                 return 0;
1282         if (chan->generatordata) {
1283                 if (chan->writeinterrupt)
1284                         ast_deactivate_generator(chan);
1285                 else
1286                         return 0;
1287         }
1288         if (chan->fout & 0x80000000)
1289                 ast_frame_dump(chan->name, fr, ">>");
1290         CHECK_BLOCKING(chan);
1291         switch(fr->frametype) {
1292         case AST_FRAME_CONTROL:
1293                 /* XXX Interpret control frames XXX */
1294                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1295                 break;
1296         case AST_FRAME_DTMF:
1297                 res = do_senddigit(chan,fr->subclass);
1298                 break;
1299         case AST_FRAME_TEXT:
1300                 if (chan->pvt->send_text)
1301                         res = chan->pvt->send_text(chan, (char *) fr->data);
1302                 break;
1303         default:
1304                 if (chan->pvt->write) {
1305                         if (chan->pvt->writetrans) {
1306                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1307                         } else
1308                                 f = fr;
1309                         if (f)  
1310                         {
1311                                 res = chan->pvt->write(chan, f);
1312                                 if( chan->monitor &&
1313                                                 chan->monitor->write_stream &&
1314                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1315                                         if( ast_writestream( chan->monitor->write_stream, f ) < 0 ) {
1316                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1317                                         }
1318                                 }
1319                         }
1320                         else
1321                                 res = 0;
1322                 }
1323         }
1324         if (f && (f != fr))
1325                 ast_frfree(f);
1326         chan->blocking = 0;
1327         /* Consider a write failure to force a soft hangup */
1328         if (res < 0)
1329                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1330         else {
1331                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1332                         chan->fout &= 0x80000000;
1333                 else
1334                         chan->fout++;
1335                 chan->fout++;
1336         }
1337         return res;
1338 }
1339
1340 int ast_set_write_format(struct ast_channel *chan, int fmts)
1341 {
1342         int fmt;
1343         int native;
1344         int res;
1345         
1346         native = chan->nativeformats;
1347         fmt = fmts;
1348         
1349         res = ast_translator_best_choice(&native, &fmt);
1350         if (res < 0) {
1351                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1352                 return -1;
1353         }
1354         
1355         /* Now we have a good choice for both.  We'll write using our native format. */
1356         chan->pvt->rawwriteformat = native;
1357         /* User perspective is fmt */
1358         chan->writeformat = fmt;
1359         /* Free any write translation we have right now */
1360         if (chan->pvt->writetrans)
1361                 ast_translator_free_path(chan->pvt->writetrans);
1362         /* Build a translation path from the user write format to the raw writing format */
1363         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1364         if (option_debug)
1365                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1366         return 0;
1367 }
1368
1369 int ast_set_read_format(struct ast_channel *chan, int fmts)
1370 {
1371         int fmt;
1372         int native;
1373         int res;
1374         
1375         native = chan->nativeformats;
1376         fmt = fmts;
1377         /* Find a translation path from the native read format to one of the user's read formats */
1378         res = ast_translator_best_choice(&fmt, &native);
1379         if (res < 0) {
1380                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1381                 return -1;
1382         }
1383         
1384         /* Now we have a good choice for both.  We'll write using our native format. */
1385         chan->pvt->rawreadformat = native;
1386         /* User perspective is fmt */
1387         chan->readformat = fmt;
1388         /* Free any read translation we have right now */
1389         if (chan->pvt->readtrans)
1390                 ast_translator_free_path(chan->pvt->readtrans);
1391         /* Build a translation path from the raw read format to the user reading format */
1392         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1393         if (option_debug)
1394                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1395         return 0;
1396 }
1397
1398 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1399 {
1400         int state = 0;
1401         struct ast_channel *chan;
1402         struct ast_frame *f;
1403         int res;
1404         
1405         chan = ast_request(type, format, data);
1406         if (chan) {
1407                 if (callerid)
1408                         ast_set_callerid(chan, callerid, 1);
1409                 if (!ast_call(chan, data, 0)) {
1410                         while(timeout && (chan->_state != AST_STATE_UP)) {
1411                                 res = ast_waitfor(chan, timeout);
1412                                 if (res < 0) {
1413                                         /* Something not cool, or timed out */
1414                                         ast_hangup(chan);
1415                                         chan = NULL;
1416                                         break;
1417                                 }
1418                                 /* If done, break out */
1419                                 if (!res)
1420                                         break;
1421                                 if (timeout > -1)
1422                                         timeout = res;
1423                                 f = ast_read(chan);
1424                                 if (!f) {
1425                                         state = AST_CONTROL_HANGUP;
1426                                         ast_hangup(chan);
1427                                         chan = NULL;
1428                                         break;
1429                                 }
1430                                 if (f->frametype == AST_FRAME_CONTROL) {
1431                                         if (f->subclass == AST_CONTROL_RINGING)
1432                                                 state = AST_CONTROL_RINGING;
1433                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1434                                                 state = f->subclass;
1435                                                 break;
1436                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1437                                                 state = f->subclass;
1438                                                 break;
1439                                         } else {
1440                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1441                                         }
1442                                 }
1443                                 ast_frfree(f);
1444                         }
1445                 } else {
1446                         ast_hangup(chan);
1447                         chan = NULL;
1448                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1449                 }
1450         } else
1451                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1452         if (chan && (chan->_state == AST_STATE_UP))
1453                 state = AST_CONTROL_ANSWER;
1454         if (outstate)
1455                 *outstate = state;
1456         return chan;
1457 }
1458
1459 struct ast_channel *ast_request(char *type, int format, void *data)
1460 {
1461         struct chanlist *chan;
1462         struct ast_channel *c = NULL;
1463         int capabilities;
1464         int fmt;
1465         int res;
1466         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1467                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1468                 return NULL;
1469         }
1470         chan = backends;
1471         while(chan) {
1472                 if (!strcasecmp(type, chan->type)) {
1473                         capabilities = chan->capabilities;
1474                         fmt = format;
1475                         res = ast_translator_best_choice(&fmt, &capabilities);
1476                         if (res < 0) {
1477                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1478                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1479                                 return NULL;
1480                         }
1481                         PTHREAD_MUTEX_UNLOCK(&chlock);
1482                         if (chan->requester)
1483                                 c = chan->requester(type, capabilities, data);
1484                         if (c) {
1485 //                              ast_device_state_changed(c->name);
1486                                 manager_event(EVENT_FLAG_CALL, "Newchannel",
1487                                 "Channel: %s\r\n"
1488                                 "State: %s\r\n"
1489                                 "Callerid: %s\r\n",
1490                                 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>");
1491                         }
1492                         return c;
1493                 }
1494                 chan = chan->next;
1495         }
1496         if (!chan)
1497                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1498         PTHREAD_MUTEX_UNLOCK(&chlock);
1499         return c;
1500 }
1501
1502 int ast_parse_device_state(char *device)
1503 {
1504         char name[AST_CHANNEL_NAME] = "";
1505         char *cut;
1506         struct ast_channel *chan;
1507
1508         chan = ast_channel_walk(NULL);
1509         while (chan) {
1510                 strncpy(name, chan->name, sizeof(name)-1);
1511                 cut = strchr(name,'-');
1512                 if (cut)
1513                         *cut = 0;
1514                 if (!strcmp(name, device))
1515                         return AST_DEVICE_INUSE;
1516                 chan = ast_channel_walk(chan);
1517         }
1518         return AST_DEVICE_UNKNOWN;
1519 }
1520
1521 int ast_device_state(char *device)
1522 {
1523         char tech[AST_MAX_EXTENSION] = "";
1524         char *number;
1525         struct chanlist *chanls;
1526         int res = 0;
1527         
1528         strncpy(tech, device, sizeof(tech)-1);
1529         number = strchr(tech, '/');
1530         if (!number) {
1531             return AST_DEVICE_INVALID;
1532         }
1533         *number = 0;
1534         number++;
1535                 
1536         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1537                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1538                 return -1;
1539         }
1540         chanls = backends;
1541         while(chanls) {
1542                 if (!strcasecmp(tech, chanls->type)) {
1543                         PTHREAD_MUTEX_UNLOCK(&chlock);
1544                         if (!chanls->devicestate) 
1545                                 return ast_parse_device_state(device);
1546                         else {
1547                                 res = chanls->devicestate(number);
1548                                 if (res == AST_DEVICE_UNKNOWN)
1549                                         return ast_parse_device_state(device);
1550                                 else
1551                                         return res;
1552                         }
1553                 }
1554                 chanls = chanls->next;
1555         }
1556         PTHREAD_MUTEX_UNLOCK(&chlock);
1557         return AST_DEVICE_INVALID;
1558 }
1559
1560 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1561 {
1562         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1563            If the remote end does not answer within the timeout, then do NOT hang up, but 
1564            return anyway.  */
1565         int res = -1;
1566         /* Stop if we're a zombie or need a soft hangup */
1567         ast_pthread_mutex_lock(&chan->lock);
1568         if (!chan->zombie && !ast_check_hangup(chan)) 
1569                 if (chan->pvt->call)
1570                         res = chan->pvt->call(chan, addr, timeout);
1571         pthread_mutex_unlock(&chan->lock);
1572         return res;
1573 }
1574
1575 int ast_transfer(struct ast_channel *chan, char *dest) 
1576 {
1577         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1578            If the remote end does not answer within the timeout, then do NOT hang up, but 
1579            return anyway.  */
1580         int res = -1;
1581         /* Stop if we're a zombie or need a soft hangup */
1582         ast_pthread_mutex_lock(&chan->lock);
1583         if (!chan->zombie && !ast_check_hangup(chan)) {
1584                 if (chan->pvt->transfer) {
1585                         res = chan->pvt->transfer(chan, dest);
1586                         if (!res)
1587                                 res = 1;
1588                 } else
1589                         res = 0;
1590         }
1591         pthread_mutex_unlock(&chan->lock);
1592         return res;
1593 }
1594
1595 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1596 {
1597         int pos=0;
1598         int to = ftimeout;
1599         char d;
1600         /* XXX Merge with full version? XXX */
1601         /* Stop if we're a zombie or need a soft hangup */
1602         if (c->zombie || ast_check_hangup(c)) 
1603                 return -1;
1604         if (!len)
1605                 return -1;
1606         do {
1607                 if (c->streamid > -1) {
1608                         d = ast_waitstream(c, AST_DIGIT_ANY);
1609                         ast_stopstream(c);
1610                         usleep(1000);
1611                         if (!d)
1612                                 d = ast_waitfordigit(c, to);
1613                 } else {
1614                         d = ast_waitfordigit(c, to);
1615                 }
1616                 if (d < 0)
1617                         return -1;
1618                 if (d == 0) {
1619                         s[pos]='\0';
1620                         return 1;
1621                 }
1622                 if (!strchr(enders, d))
1623                         s[pos++] = d;
1624                 if (strchr(enders, d) || (pos >= len)) {
1625                         s[pos]='\0';
1626                         return 0;
1627                 }
1628                 to = timeout;
1629         } while(1);
1630         /* Never reached */
1631         return 0;
1632 }
1633
1634 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1635 {
1636         int pos=0;
1637         int to = ftimeout;
1638         char d;
1639         /* Stop if we're a zombie or need a soft hangup */
1640         if (c->zombie || ast_check_hangup(c)) 
1641                 return -1;
1642         if (!len)
1643                 return -1;
1644         do {
1645                 if (c->streamid > -1) {
1646                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1647                         ast_stopstream(c);
1648                         usleep(1000);
1649                         if (!d)
1650                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1651                 } else {
1652                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1653                 }
1654                 if (d < 0)
1655                         return -1;
1656                 if (d == 0) {
1657                         s[pos]='\0';
1658                         return 1;
1659                 }
1660                 if (d == 1) {
1661                         s[pos]='\0';
1662                         return 2;
1663                 }
1664                 if (!strchr(enders, d))
1665                         s[pos++] = d;
1666                 if (strchr(enders, d) || (pos >= len)) {
1667                         s[pos]='\0';
1668                         return 0;
1669                 }
1670                 to = timeout;
1671         } while(1);
1672         /* Never reached */
1673         return 0;
1674 }
1675
1676 int ast_channel_supports_html(struct ast_channel *chan)
1677 {
1678         if (chan->pvt->send_html)
1679                 return 1;
1680         return 0;
1681 }
1682
1683 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1684 {
1685         if (chan->pvt->send_html)
1686                 return chan->pvt->send_html(chan, subclass, data, datalen);
1687         return -1;
1688 }
1689
1690 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1691 {
1692         if (chan->pvt->send_html)
1693                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1694         return -1;
1695 }
1696
1697 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1698 {
1699         int peerf;
1700         int chanf;
1701         int res;
1702         peerf = peer->nativeformats;
1703         chanf = chan->nativeformats;
1704         res = ast_translator_best_choice(&peerf, &chanf);
1705         if (res < 0) {
1706                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1707                 return -1;
1708         }
1709         /* Set read format on channel */
1710         res = ast_set_read_format(chan, peerf);
1711         if (res < 0) {
1712                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1713                 return -1;
1714         }
1715         /* Set write format on peer channel */
1716         res = ast_set_write_format(peer, peerf);
1717         if (res < 0) {
1718                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1719                 return -1;
1720         }
1721         /* Now we go the other way */
1722         peerf = peer->nativeformats;
1723         chanf = chan->nativeformats;
1724         res = ast_translator_best_choice(&chanf, &peerf);
1725         if (res < 0) {
1726                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1727                 return -1;
1728         }
1729         /* Set writeformat on channel */
1730         res = ast_set_write_format(chan, chanf);
1731         if (res < 0) {
1732                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1733                 return -1;
1734         }
1735         /* Set read format on peer channel */
1736         res = ast_set_read_format(peer, chanf);
1737         if (res < 0) {
1738                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1739                 return -1;
1740         }
1741         return 0;
1742 }
1743
1744 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1745 {
1746         struct ast_frame null = { AST_FRAME_NULL, };
1747         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1748                 clone->name, original->name);
1749         if (original->masq) {
1750                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1751                         original->masq->name, original->name);
1752                 return -1;
1753         }
1754         if (clone->masqr) {
1755                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1756                         clone->name, clone->masqr->name);
1757                 return -1;
1758         }
1759         original->masq = clone;
1760         clone->masqr = original;
1761         /* XXX can't really hold the lock here, but at the same time, it' s
1762            not really safe not to XXX */
1763         ast_queue_frame(original, &null, 0);
1764         ast_queue_frame(clone, &null, 0);
1765         return 0;
1766 }
1767
1768 void ast_change_name(struct ast_channel *chan, char *newname)
1769 {
1770         char tmp[256];
1771         strncpy(tmp, chan->name, 256);
1772         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1773         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", tmp, chan->name);
1774 }
1775
1776 static int ast_do_masquerade(struct ast_channel *original)
1777 {
1778         int x;
1779         int res=0;
1780         char *tmp;
1781         void *tmpv;
1782         struct ast_channel_pvt *p;
1783         struct ast_channel *clone = original->masq;
1784         int rformat = original->readformat;
1785         int wformat = original->writeformat;
1786         char newn[100];
1787         char orig[100];
1788         char masqn[100];
1789         char zombn[100];
1790         
1791 #if 1
1792         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1793                 clone->name, clone->_state, original->name, original->_state);
1794 #endif
1795         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1796            the clone channel into the original channel.  Start by killing off the original
1797            channel's backend.   I'm not sure we're going to keep this function, because 
1798            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1799
1800         /* Having remembered the original read/write formats, we turn off any translation on either
1801            one */
1802         free_translation(clone);
1803         free_translation(original);
1804
1805         /* We need the clone's lock, too */
1806         ast_pthread_mutex_lock(&clone->lock);
1807
1808         /* Unlink the masquerade */
1809         original->masq = NULL;
1810         clone->masqr = NULL;
1811         
1812         /* Save the original name */
1813         strncpy(orig, original->name, sizeof(orig) - 1);
1814         /* Save the new name */
1815         strncpy(newn, clone->name, sizeof(newn) - 1);
1816         /* Create the masq name */
1817         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1818                 
1819         /* Copy the name from the clone channel */
1820         strncpy(original->name, newn, sizeof(original->name)-1);
1821
1822         /* Mangle the name of the clone channel */
1823         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1824         
1825         /* Notify any managers of the change, first the masq then the other */
1826         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1827         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1828
1829         /* Swap the guts */     
1830         p = original->pvt;
1831         original->pvt = clone->pvt;
1832         clone->pvt = p;
1833         
1834         clone->_softhangup = AST_SOFTHANGUP_DEV;
1835
1836
1837         if (clone->pvt->fixup){
1838                 res = clone->pvt->fixup(original, clone);
1839                 if (res) 
1840                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1841         }
1842
1843         /* Start by disconnecting the original's physical side */
1844         if (clone->pvt->hangup)
1845                 res = clone->pvt->hangup(clone);
1846         if (res) {
1847                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1848                 pthread_mutex_unlock(&clone->lock);
1849                 return -1;
1850         }
1851         
1852         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
1853         /* Mangle the name of the clone channel */
1854         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
1855         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
1856
1857         /* Keep the same language.  */
1858         /* Update the type. */
1859         original->type = clone->type;
1860         /* Copy the FD's */
1861         for (x=0;x<AST_MAX_FDS;x++)
1862                 original->fds[x] = clone->fds[x];
1863         /* Move the variables */
1864         tmpv = original->varshead.first;
1865         original->varshead.first = clone->varshead.first;
1866         clone->varshead.first = tmpv;
1867         /* Presense of ADSI capable CPE follows clone */
1868         original->adsicpe = clone->adsicpe;
1869         /* Bridge remains the same */
1870         /* CDR fields remain the same */
1871         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1872         /* Application and data remain the same */
1873         /* Clone exception  becomes real one, as with fdno */
1874         original->exception = clone->exception;
1875         original->fdno = clone->fdno;
1876         /* Schedule context remains the same */
1877         /* Stream stuff stays the same */
1878         /* Keep the original state.  The fixup code will need to work with it most likely */
1879
1880         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1881            fields back into the defunct 'clone' so that they will be freed when
1882            ast_frfree is eventually called */
1883         tmp = original->dnid;
1884         original->dnid = clone->dnid;
1885         clone->dnid = tmp;
1886         
1887         tmp = original->callerid;
1888         original->callerid = clone->callerid;
1889         clone->callerid = tmp;
1890         
1891         /* Our native formats are different now */
1892         original->nativeformats = clone->nativeformats;
1893
1894         /* And of course, so does our current state.  Note we need not
1895            call ast_setstate since the event manager doesn't really consider
1896            these separate */
1897         original->_state = clone->_state;
1898         
1899         /* Context, extension, priority, app data, jump table,  remain the same */
1900         /* pvt switches.  pbx stays the same, as does next */
1901         
1902         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1903            a zombie so nothing tries to touch it.  If it's already been marked as a
1904            zombie, then free it now (since it already is considered invalid). */
1905         if (clone->zombie) {
1906                 pthread_mutex_unlock(&clone->lock);
1907                 ast_channel_free(clone);
1908                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
1909         } else {
1910                 clone->zombie=1;
1911                 pthread_mutex_unlock(&clone->lock);
1912         }
1913         /* Set the write format */
1914         ast_set_write_format(original, wformat);
1915
1916         /* Set the read format */
1917         ast_set_read_format(original, rformat);
1918
1919         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1920
1921         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1922            can fix up everything as best as possible */
1923         if (original->pvt->fixup) {
1924                 res = original->pvt->fixup(clone, original);
1925                 if (res) {
1926                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1927                                 original->type, original->name);
1928                         return -1;
1929                 }
1930         } else
1931                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
1932                         original->type, original->name);
1933         /* Signal any blocker */
1934         if (original->blocking)
1935                 pthread_kill(original->blocker, SIGURG);
1936         return 0;
1937 }
1938
1939 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
1940 {
1941         if (chan->callerid)
1942                 free(chan->callerid);
1943         if (anitoo && chan->ani)
1944                 free(chan->ani);
1945         if (callerid) {
1946                 chan->callerid = strdup(callerid);
1947                 if (anitoo)
1948                         chan->ani = strdup(callerid);
1949         } else {
1950                 chan->callerid = NULL;
1951                 if (anitoo)
1952                         chan->ani = NULL;
1953         }
1954         if (chan->cdr)
1955                 ast_cdr_setcid(chan->cdr, chan);
1956         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
1957                                 "Channel: %s\r\n"
1958                                 "Callerid: %s\r\n",
1959                                 chan->name, chan->callerid ? 
1960                                 chan->callerid : "<Unknown>");
1961 }
1962
1963 int ast_setstate(struct ast_channel *chan, int state)
1964 {
1965         if (chan->_state != state) {
1966                 int oldstate = chan->_state;
1967                 chan->_state = state;
1968                 if (oldstate == AST_STATE_DOWN) {
1969                         ast_device_state_changed(chan->name);
1970                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1971                         "Channel: %s\r\n"
1972                         "State: %s\r\n"
1973                         "Callerid: %s\r\n",
1974                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1975                 } else {
1976                         manager_event(EVENT_FLAG_CALL, "Newstate", 
1977                                 "Channel: %s\r\n"
1978                                 "State: %s\r\n"
1979                                 "Callerid: %s\r\n",
1980                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>");
1981                 }
1982         }
1983         return 0;
1984 }
1985
1986 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1987 {
1988         /* Copy voice back and forth between the two channels.  Give the peer
1989            the ability to transfer calls with '#<extension' syntax. */
1990         struct ast_channel *cs[3];
1991         int to = -1;
1992         struct ast_frame *f;
1993         struct ast_channel *who = NULL;
1994         int res;
1995         int nativefailed=0;
1996
1997         /* Stop if we're a zombie or need a soft hangup */
1998         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
1999                 return -1;
2000         if (c0->bridge) {
2001                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2002                         c0->name, c0->bridge->name);
2003                 return -1;
2004         }
2005         if (c1->bridge) {
2006                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2007                         c1->name, c1->bridge->name);
2008                 return -1;
2009         }
2010         
2011         /* Keep track of bridge */
2012         c0->bridge = c1;
2013         c1->bridge = c0;
2014         cs[0] = c0;
2015         cs[1] = c1;
2016         
2017         manager_event(EVENT_FLAG_CALL, "Link", 
2018                         "Channel1: %s\r\n"
2019                         "Channel2: %s\r\n",
2020                         c0->name, c1->name);
2021
2022         for (/* ever */;;) {
2023                 /* Stop if we're a zombie or need a soft hangup */
2024                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
2025                         *fo = NULL;
2026                         if (who) *rc = who;
2027                         res = 0;
2028                         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");
2029                         break;
2030                 }
2031                 if (c0->pvt->bridge && 
2032                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2033                                 /* Looks like they share a bridge code */
2034                         if (option_verbose > 2) 
2035                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2036                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2037                                 c0->bridge = NULL;
2038                                 c1->bridge = NULL;
2039                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2040                                         "Channel1: %s\r\n"
2041                                         "Channel2: %s\r\n",
2042                                         c0->name, c1->name);
2043                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2044                                 return 0;
2045                         }
2046                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2047                            my not wanting to bridge */
2048                         if ((res != -2) && (res != -3))
2049                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2050                         if (res != -3) nativefailed++;
2051                 }
2052         
2053                         
2054                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2055                         !(c0->generator || c1->generator))  {
2056                         if (ast_channel_make_compatible(c0, c1)) {
2057                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2058                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2059                                         "Channel1: %s\r\n"
2060                                         "Channel2: %s\r\n",
2061                                         c0->name, c1->name);
2062                                 return -1;
2063                         }
2064                 }
2065                 who = ast_waitfor_n(cs, 2, &to);
2066                 if (!who) {
2067                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2068                         continue;
2069                 }
2070                 f = ast_read(who);
2071                 if (!f) {
2072                         *fo = NULL;
2073                         *rc = who;
2074                         res = 0;
2075                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2076                         break;
2077                 }
2078
2079                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2080                         *fo = f;
2081                         *rc = who;
2082                         res =  0;
2083                         ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2084                         break;
2085                 }
2086                 if ((f->frametype == AST_FRAME_VOICE) ||
2087                         (f->frametype == AST_FRAME_TEXT) ||
2088                         (f->frametype == AST_FRAME_VIDEO) || 
2089                         (f->frametype == AST_FRAME_IMAGE) ||
2090                         (f->frametype == AST_FRAME_DTMF)) {
2091                         if ((f->frametype == AST_FRAME_DTMF) && 
2092                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2093                                 if ((who == c0)) {
2094                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2095                                                 *rc = c0;
2096                                                 *fo = f;
2097                                                 /* Take out of conference mode */
2098                                                 res = 0;
2099                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2100                                                 break;
2101                                         } else 
2102                                                 goto tackygoto;
2103                                 } else
2104                                 if ((who == c1)) {
2105                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2106                                                 *rc = c1;
2107                                                 *fo = f;
2108                                                 res =  0;
2109                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2110                                                 break;
2111                                         } else
2112                                                 goto tackygoto;
2113                                 }
2114                         } else {
2115 #if 0
2116                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2117                                 if (who == last) 
2118                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2119                                 last = who;
2120 #endif
2121 tackygoto:
2122                                 /* Don't copy packets if there is a generator on either one, since they're
2123                                    not supposed to be listening anyway */
2124                                 if (who == c0) 
2125                                         ast_write(c1, f);
2126                                 else 
2127                                         ast_write(c0, f);
2128                         }
2129                         ast_frfree(f);
2130                 } else
2131                         ast_frfree(f);
2132                 /* Swap who gets priority */
2133                 cs[2] = cs[0];
2134                 cs[0] = cs[1];
2135                 cs[1] = cs[2];
2136         }
2137         c0->bridge = NULL;
2138         c1->bridge = NULL;
2139         manager_event(EVENT_FLAG_CALL, "Unlink", 
2140                                         "Channel1: %s\r\n"
2141                                         "Channel2: %s\r\n",
2142                                         c0->name, c1->name);
2143         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2144         return res;
2145 }
2146
2147 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2148 {
2149         int res;
2150         if (chan->pvt->setoption) {
2151                 res = chan->pvt->setoption(chan, option, data, datalen);
2152                 if (res < 0)
2153                         return res;
2154         } else {
2155                 errno = ENOSYS;
2156                 return -1;
2157         }
2158         if (block) {
2159                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2160                    intermediate packets. XXX */
2161                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2162                 return -1;
2163         }
2164         return 0;
2165 }
2166
2167 struct tonepair_def {
2168         int freq1;
2169         int freq2;
2170         int duration;
2171         int vol;
2172 };
2173
2174 struct tonepair_state {
2175         float freq1;
2176         float freq2;
2177         float vol;
2178         int duration;
2179         int pos;
2180         int origwfmt;
2181         struct ast_frame f;
2182         unsigned char offset[AST_FRIENDLY_OFFSET];
2183         short data[4000];
2184 };
2185
2186 static void tonepair_release(struct ast_channel *chan, void *params)
2187 {
2188         struct tonepair_state *ts = params;
2189         if (chan) {
2190                 ast_set_write_format(chan, ts->origwfmt);
2191         }
2192         free(ts);
2193 }
2194
2195 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2196 {
2197         struct tonepair_state *ts;
2198         struct tonepair_def *td = params;
2199         ts = malloc(sizeof(struct tonepair_state));
2200         if (!ts)
2201                 return NULL;
2202         memset(ts, 0, sizeof(struct tonepair_state));
2203         ts->origwfmt = chan->writeformat;
2204         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2205                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2206                 tonepair_release(NULL, ts);
2207                 ts = NULL;
2208         } else {
2209                 ts->freq1 = td->freq1;
2210                 ts->freq2 = td->freq2;
2211                 ts->duration = td->duration;
2212                 ts->vol = td->vol;
2213         }
2214         /* Let interrupts interrupt :) */
2215         chan->writeinterrupt = 1;
2216         return ts;
2217 }
2218
2219 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2220 {
2221         struct tonepair_state *ts = data;
2222         int x;
2223
2224         /* we need to prepare a frame with 16 * timelen samples as we're 
2225          * generating SLIN audio
2226          */
2227         len = samples * 2;
2228
2229         if (len > sizeof(ts->data) / 2 - 1) {
2230                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2231                 return -1;
2232         }
2233         memset(&ts->f, 0, sizeof(ts->f));
2234         for (x=0;x<len/2;x++) {
2235                 ts->data[x] = ts->vol * (
2236                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2237                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2238                         );
2239         }
2240         ts->f.frametype = AST_FRAME_VOICE;
2241         ts->f.subclass = AST_FORMAT_SLINEAR;
2242         ts->f.datalen = len;
2243         ts->f.samples = samples;
2244         ts->f.offset = AST_FRIENDLY_OFFSET;
2245         ts->f.data = ts->data;
2246         ast_write(chan, &ts->f);
2247         ts->pos += x;
2248         if (ts->duration > 0) {
2249                 if (ts->pos >= ts->duration * 8)
2250                         return -1;
2251         }
2252         return 0;
2253 }
2254
2255 static struct ast_generator tonepair = {
2256         alloc: tonepair_alloc,
2257         release: tonepair_release,
2258         generate: tonepair_generator,
2259 };
2260
2261 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2262 {
2263         struct tonepair_def d = { 0, };
2264         d.freq1 = freq1;
2265         d.freq2 = freq2;
2266         d.duration = duration;
2267         if (vol < 1)
2268                 d.vol = 8192;
2269         else
2270                 d.vol = vol;
2271         if (ast_activate_generator(chan, &tonepair, &d))
2272                 return -1;
2273         return 0;
2274 }
2275
2276 void ast_tonepair_stop(struct ast_channel *chan)
2277 {
2278         ast_deactivate_generator(chan);
2279 }
2280
2281 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2282 {
2283         struct ast_frame *f;
2284         int res;
2285         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2286                 return res;
2287
2288         /* Give us some wiggle room */
2289         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2290                 f = ast_read(chan);
2291                 if (f)
2292                         ast_frfree(f);
2293                 else
2294                         return -1;
2295         }
2296         return 0;
2297 }
2298
2299