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