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