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