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