5eb680d0205cb26e05f387317a894efa13f0c3e1
[asterisk/asterisk.git] / channel.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Channel Management
5  * 
6  * Copyright (C) 1999 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
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 <string.h>
17 #include <sys/time.h>
18 #include <signal.h>
19 #include <errno.h>
20 #include <unistd.h>
21 #include <math.h>                       /* For PI */
22
23 #ifdef ZAPTEL_OPTIMIZATIONS
24 #include <sys/ioctl.h>
25 #ifdef __linux__
26 #include <linux/zaptel.h>
27 #else
28 #include <zaptel.h>
29 #endif /* __linux__ */
30 #ifndef ZT_TIMERPING
31 #error "You need newer zaptel!  Please cvs update zaptel"
32 #endif
33 #endif
34
35 #include "asterisk/pbx.h"
36 #include "asterisk/frame.h"
37 #include "asterisk/sched.h"
38 #include "asterisk/options.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/musiconhold.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/say.h"
43 #include "asterisk/file.h"
44 #include "asterisk/cli.h"
45 #include "asterisk/translate.h"
46 #include "asterisk/manager.h"
47 #include "asterisk/chanvars.h"
48 #include "asterisk/linkedlists.h"
49 #include "asterisk/indications.h"
50 #include "asterisk/monitor.h"
51 #include "asterisk/causes.h"
52 #include "asterisk/utils.h"
53 #include "asterisk/lock.h"
54 #include "asterisk/app.h"
55 #include "asterisk/transcap.h"
56 #include "asterisk.h"
57
58 /* uncomment if you have problems with 'monitoring' synchronized files */
59 #if 0
60 #define MONITOR_CONSTANT_DELAY
61 #define MONITOR_DELAY   150 * 8         /* 150 ms of MONITORING DELAY */
62 #endif
63
64 static int shutting_down = 0;
65 static int uniqueint = 0;
66
67 unsigned long global_fin = 0, global_fout = 0;
68
69 /* XXX Lock appropriately in more functions XXX */
70
71 struct chanlist {
72         const struct ast_channel_tech *tech;
73         struct chanlist *next;
74 } *backends = NULL;
75 struct ast_channel *channels = NULL;
76
77 /* Protect the channel list (highly unlikely that two things would change
78    it at the same time, but still! */
79    
80 AST_MUTEX_DEFINE_STATIC(chlock);
81
82 static int show_channeltypes(int fd, int argc, char *argv[])
83 {
84 #define FORMAT  "%-7.7s  %-50.50s\n"
85         struct chanlist *cl = backends;
86         ast_cli(fd, FORMAT, "Type", "Description");
87         ast_cli(fd, FORMAT, "------", "-----------");
88         if (ast_mutex_lock(&chlock)) {
89                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
90                 return -1;
91         }
92         while (cl) {
93                 ast_cli(fd, FORMAT, cl->tech->type, cl->tech->description);
94                 cl = cl->next;
95         }
96         ast_mutex_unlock(&chlock);
97         return RESULT_SUCCESS;
98
99 }
100
101 static char show_channeltypes_usage[] = 
102 "Usage: show channeltypes\n"
103 "       Shows available channel types registered in your Asterisk server.\n";
104
105 static struct ast_cli_entry cli_show_channeltypes = 
106         { { "show", "channeltypes", NULL }, show_channeltypes, "Show available channel types", show_channeltypes_usage };
107
108 int ast_check_hangup(struct ast_channel *chan)
109 {
110 time_t  myt;
111
112           /* if soft hangup flag, return true */
113         if (chan->_softhangup) return 1;
114           /* if no technology private data, return true */
115         if (!chan->tech_pvt) return 1;
116           /* if no hangup scheduled, just return here */
117         if (!chan->whentohangup) return 0;
118         time(&myt); /* get current time */
119           /* return, if not yet */
120         if (chan->whentohangup > myt) return 0;
121         chan->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
122         return 1;
123 }
124
125 static int ast_check_hangup_locked(struct ast_channel *chan)
126 {
127         int res;
128         ast_mutex_lock(&chan->lock);
129         res = ast_check_hangup(chan);
130         ast_mutex_unlock(&chan->lock);
131         return res;
132 }
133
134 void ast_begin_shutdown(int hangup)
135 {
136         struct ast_channel *c;
137         shutting_down = 1;
138         if (hangup) {
139                 ast_mutex_lock(&chlock);
140                 c = channels;
141                 while(c) {
142                         ast_softhangup(c, AST_SOFTHANGUP_SHUTDOWN);
143                         c = c->next;
144                 }
145                 ast_mutex_unlock(&chlock);
146         }
147 }
148
149 int ast_active_channels(void)
150 {
151         struct ast_channel *c;
152         int cnt = 0;
153         ast_mutex_lock(&chlock);
154         c = channels;
155         while(c) {
156                 cnt++;
157                 c = c->next;
158         }
159         ast_mutex_unlock(&chlock);
160         return cnt;
161 }
162
163 void ast_cancel_shutdown(void)
164 {
165         shutting_down = 0;
166 }
167
168 int ast_shutting_down(void)
169 {
170         return shutting_down;
171 }
172
173 void ast_channel_setwhentohangup(struct ast_channel *chan, time_t offset)
174 {
175         time_t  myt;
176
177         time(&myt);
178         if (offset)
179                 chan->whentohangup = myt + offset;
180         else
181                 chan->whentohangup = 0;
182         return;
183 }
184
185 int ast_channel_register(const struct ast_channel_tech *tech)
186 {
187         struct chanlist *chan;
188
189         ast_mutex_lock(&chlock);
190
191         chan = backends;
192         while (chan) {
193                 if (!strcasecmp(tech->type, chan->tech->type)) {
194                         ast_log(LOG_WARNING, "Already have a handler for type '%s'\n", tech->type);
195                         ast_mutex_unlock(&chlock);
196                         return -1;
197                 }
198                 chan = chan->next;
199         }
200
201         chan = malloc(sizeof(*chan));
202         if (!chan) {
203                 ast_log(LOG_WARNING, "Out of memory\n");
204                 ast_mutex_unlock(&chlock);
205                 return -1;
206         }
207         chan->tech = tech;
208         chan->next = backends;
209         backends = chan;
210
211         if (option_debug)
212                 ast_log(LOG_DEBUG, "Registered handler for '%s' (%s)\n", chan->tech->type, chan->tech->description);
213
214         if (option_verbose > 1)
215                 ast_verbose(VERBOSE_PREFIX_2 "Registered channel type '%s' (%s)\n", chan->tech->type,
216                             chan->tech->description);
217
218         ast_mutex_unlock(&chlock);
219         return 0;
220 }
221
222 char *ast_state2str(int state)
223 {
224         /* XXX Not reentrant XXX */
225         static char localtmp[256];
226         switch(state) {
227         case AST_STATE_DOWN:
228                 return "Down";
229         case AST_STATE_RESERVED:
230                 return "Rsrvd";
231         case AST_STATE_OFFHOOK:
232                 return "OffHook";
233         case AST_STATE_DIALING:
234                 return "Dialing";
235         case AST_STATE_RING:
236                 return "Ring";
237         case AST_STATE_RINGING:
238                 return "Ringing";
239         case AST_STATE_UP:
240                 return "Up";
241         case AST_STATE_BUSY:
242                 return "Busy";
243         default:
244                 snprintf(localtmp, sizeof(localtmp), "Unknown (%d)\n", state);
245                 return localtmp;
246         }
247 }
248
249 char *ast_transfercapability2str(int transfercapability)
250 {
251         switch(transfercapability) {
252         case AST_TRANS_CAP_SPEECH:
253                 return "SPEECH";
254         case AST_TRANS_CAP_DIGITAL:
255                 return "DIGITAL";
256         case AST_TRANS_CAP_RESTRICTED_DIGITAL:
257                 return "RESTRICTED_DIGITAL";
258         case AST_TRANS_CAP_3_1K_AUDIO:
259                 return "3K1AUDIO";
260         case AST_TRANS_CAP_DIGITAL_W_TONES:
261                 return "DIGITAL_W_TONES";
262         case AST_TRANS_CAP_VIDEO:
263                 return "VIDEO";
264         default:
265                 return "UNKNOWN";
266         }
267 }
268
269 int ast_best_codec(int fmts)
270 {
271         /* This just our opinion, expressed in code.  We are asked to choose
272            the best codec to use, given no information */
273         int x;
274         static int prefs[] = 
275         {
276                 /* Okay, ulaw is used by all telephony equipment, so start with it */
277                 AST_FORMAT_ULAW,
278                 /* Unless of course, you're a silly European, so then prefer ALAW */
279                 AST_FORMAT_ALAW,
280                 /* Okay, well, signed linear is easy to translate into other stuff */
281                 AST_FORMAT_SLINEAR,
282                 /* G.726 is standard ADPCM */
283                 AST_FORMAT_G726,
284                 /* ADPCM has great sound quality and is still pretty easy to translate */
285                 AST_FORMAT_ADPCM,
286                 /* Okay, we're down to vocoders now, so pick GSM because it's small and easier to
287                    translate and sounds pretty good */
288                 AST_FORMAT_GSM,
289                 /* iLBC is not too bad */
290                 AST_FORMAT_ILBC,
291                 /* Speex is free, but computationally more expensive than GSM */
292                 AST_FORMAT_SPEEX,
293                 /* Ick, LPC10 sounds terrible, but at least we have code for it, if you're tacky enough
294                    to use it */
295                 AST_FORMAT_LPC10,
296                 /* G.729a is faster than 723 and slightly less expensive */
297                 AST_FORMAT_G729A,
298                 /* Down to G.723.1 which is proprietary but at least designed for voice */
299                 AST_FORMAT_G723_1,
300         };
301         
302         
303         for (x=0;x<sizeof(prefs) / sizeof(prefs[0]); x++)
304                 if (fmts & prefs[x])
305                         return prefs[x];
306         ast_log(LOG_WARNING, "Don't know any of 0x%x formats\n", fmts);
307         return 0;
308 }
309
310 static const struct ast_channel_tech null_tech = {
311         .type = "NULL",
312         .description = "Null channel (should not see this)",
313 };
314
315 struct ast_channel *ast_channel_alloc(int needqueue)
316 {
317         struct ast_channel *tmp;
318         int x;
319         int flags;
320         struct varshead *headp;        
321                 
322
323         /* If shutting down, don't allocate any new channels */
324         if (shutting_down)
325                 return NULL;
326
327         tmp = malloc(sizeof(struct ast_channel));
328         if (!tmp) {
329                 ast_log(LOG_WARNING, "Out of memory\n");
330                 return NULL;
331         }
332
333         memset(tmp, 0, sizeof(struct ast_channel));
334         tmp->sched = sched_context_create();
335         if (!tmp->sched) {
336                 ast_log(LOG_WARNING, "Unable to create schedule context\n");
337                 free(tmp);
338                 return NULL;
339         }
340         
341         for (x=0;x<AST_MAX_FDS - 1;x++)
342                 tmp->fds[x] = -1;
343
344 #ifdef ZAPTEL_OPTIMIZATIONS
345         tmp->timingfd = open("/dev/zap/timer", O_RDWR);
346         if (tmp->timingfd > -1) {
347                 /* Check if timing interface supports new
348                    ping/pong scheme */
349                 flags = 1;
350                 if (!ioctl(tmp->timingfd, ZT_TIMERPONG, &flags))
351                         needqueue = 0;
352         }
353 #else
354         tmp->timingfd = -1;                                     
355 #endif                                  
356
357         if (needqueue) {
358                 if (pipe(tmp->alertpipe)) {
359                         ast_log(LOG_WARNING, "Alert pipe creation failed!\n");
360                         free(tmp);
361                         return NULL;
362                 } else {
363                         flags = fcntl(tmp->alertpipe[0], F_GETFL);
364                         fcntl(tmp->alertpipe[0], F_SETFL, flags | O_NONBLOCK);
365                         flags = fcntl(tmp->alertpipe[1], F_GETFL);
366                         fcntl(tmp->alertpipe[1], F_SETFL, flags | O_NONBLOCK);
367                 }
368         } else 
369                 /* Make sure we've got it done right if they don't */
370                 tmp->alertpipe[0] = tmp->alertpipe[1] = -1;
371
372         /* Always watch the alertpipe */
373         tmp->fds[AST_MAX_FDS-1] = tmp->alertpipe[0];
374         /* And timing pipe */
375         tmp->fds[AST_MAX_FDS-2] = tmp->timingfd;
376         strncpy(tmp->name, "**Unknown**", sizeof(tmp->name)-1);
377         /* Initial state */
378         tmp->_state = AST_STATE_DOWN;
379         tmp->streamid = -1;
380         tmp->appl = NULL;
381         tmp->data = NULL;
382         tmp->fin = global_fin;
383         tmp->fout = global_fout;
384         snprintf(tmp->uniqueid, sizeof(tmp->uniqueid), "%li.%d", (long)time(NULL), uniqueint++);
385         headp = &tmp->varshead;
386         ast_mutex_init(&tmp->lock);
387         AST_LIST_HEAD_INIT(headp);
388         strncpy(tmp->context, "default", sizeof(tmp->context)-1);
389         strncpy(tmp->language, defaultlanguage, sizeof(tmp->language)-1);
390         strncpy(tmp->exten, "s", sizeof(tmp->exten)-1);
391         tmp->priority = 1;
392         tmp->amaflags = ast_default_amaflags;
393         strncpy(tmp->accountcode, ast_default_accountcode, sizeof(tmp->accountcode)-1);
394
395         tmp->tech = &null_tech;
396
397         ast_mutex_lock(&chlock);
398         tmp->next = channels;
399         channels = tmp;
400
401         ast_mutex_unlock(&chlock);
402         return tmp;
403 }
404
405 int ast_queue_frame(struct ast_channel *chan, struct ast_frame *fin)
406 {
407         struct ast_frame *f;
408         struct ast_frame *prev, *cur;
409         int blah = 1;
410         int qlen = 0;
411         /* Build us a copy and free the original one */
412         f = ast_frdup(fin);
413         if (!f) {
414                 ast_log(LOG_WARNING, "Unable to duplicate frame\n");
415                 return -1;
416         }
417         ast_mutex_lock(&chan->lock);
418         prev = NULL;
419         cur = chan->readq;
420         while(cur) {
421                 if ((cur->frametype == AST_FRAME_CONTROL) && (cur->subclass == AST_CONTROL_HANGUP)) {
422                         /* Don't bother actually queueing anything after a hangup */
423                         ast_frfree(f);
424                         ast_mutex_unlock(&chan->lock);
425                         return 0;
426                 }
427                 prev = cur;
428                 cur = cur->next;
429                 qlen++;
430         }
431         /* Allow up to 96 voice frames outstanding, and up to 128 total frames */
432         if (((fin->frametype == AST_FRAME_VOICE) && (qlen > 96)) || (qlen  > 128)) {
433                 if (fin->frametype != AST_FRAME_VOICE) {
434                         ast_log(LOG_WARNING, "Exceptionally long queue length queuing to %s\n", chan->name);
435                         CRASH;
436                 } else {
437                         ast_log(LOG_DEBUG, "Dropping voice to exceptionally long queue on %s\n", chan->name);
438                         ast_frfree(f);
439                         ast_mutex_unlock(&chan->lock);
440                         return 0;
441                 }
442         }
443         if (prev)
444                 prev->next = f;
445         else
446                 chan->readq = f;
447         if (chan->alertpipe[1] > -1) {
448                 if (write(chan->alertpipe[1], &blah, sizeof(blah)) != sizeof(blah))
449                         ast_log(LOG_WARNING, "Unable to write to alert pipe on %s, frametype/subclass %d/%d (qlen = %d): %s!\n",
450                                 chan->name, f->frametype, f->subclass, qlen, strerror(errno));
451 #ifdef ZAPTEL_OPTIMIZATIONS
452         } else if (chan->timingfd > -1) {
453                 ioctl(chan->timingfd, ZT_TIMERPING, &blah);
454 #endif                          
455         } else if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
456                 pthread_kill(chan->blocker, SIGURG);
457         }
458         ast_mutex_unlock(&chan->lock);
459         return 0;
460 }
461
462 int ast_queue_hangup(struct ast_channel *chan)
463 {
464         struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP };
465         chan->_softhangup |= AST_SOFTHANGUP_DEV;
466         return ast_queue_frame(chan, &f);
467 }
468
469 int ast_queue_control(struct ast_channel *chan, int control)
470 {
471         struct ast_frame f = { AST_FRAME_CONTROL, };
472         f.subclass = control;
473         return ast_queue_frame(chan, &f);
474 }
475
476 int ast_channel_defer_dtmf(struct ast_channel *chan)
477 {
478         int pre = 0;
479         if (chan) {
480                 pre = ast_test_flag(chan, AST_FLAG_DEFER_DTMF);
481                 ast_set_flag(chan, AST_FLAG_DEFER_DTMF);
482         }
483         return pre;
484 }
485
486 void ast_channel_undefer_dtmf(struct ast_channel *chan)
487 {
488         if (chan)
489                 ast_clear_flag(chan, AST_FLAG_DEFER_DTMF);
490 }
491
492 struct ast_channel *ast_channel_walk_locked(struct ast_channel *prev)
493 {
494         /* Returns next channel (locked) */
495         struct ast_channel *l, *ret;
496         int retries = 0;        
497 retry:
498         ret=NULL;
499         ast_mutex_lock(&chlock);
500         l = channels;
501         if (!prev) {
502                 if (l) {
503                         if (ast_mutex_trylock(&l->lock)) {
504                                 if (retries < 10)
505                                         ast_log(LOG_DEBUG, "Avoiding initial deadlock for '%s'\n", l->name);
506                                 else
507                                         ast_log(LOG_WARNING, "Avoided initial deadlock for '%s', %d retries!\n", l->name, retries);
508                                 ast_mutex_unlock(&chlock);
509                                 if (retries < 10) {
510                                         usleep(1);
511                                         retries++;
512                                         goto retry;
513                                 } else
514                                         return NULL;
515                         }
516                 }
517                 ast_mutex_unlock(&chlock);
518                 return l;
519         }
520         while(l) {
521                 if (l == prev)
522                         ret = l->next;
523                 l = l->next;
524         }
525         if (ret) {
526                 if (ast_mutex_trylock(&ret->lock)) {
527                         if (retries < 10)
528                                 ast_log(LOG_DEBUG, "Avoiding deadlock for '%s'\n", ret->name);
529                         else
530                                 ast_log(LOG_WARNING, "Avoided deadlock for '%s', %d retries!\n", ret->name, retries);
531                         ast_mutex_unlock(&chlock);
532                         if (retries < 10) {
533                                 usleep(1);
534                                 retries++;
535                                 goto retry;
536                         } else
537                                 return NULL;
538                 }
539         }
540         ast_mutex_unlock(&chlock);
541         return ret;
542         
543 }
544
545 struct ast_channel *ast_get_channel_by_name_locked(char *channame)
546 {
547         struct ast_channel *chan;
548         chan = ast_channel_walk_locked(NULL);
549         while(chan) {
550                 if (!strcasecmp(chan->name, channame))
551                         return chan;
552                 ast_mutex_unlock(&chan->lock);
553                 chan = ast_channel_walk_locked(chan);
554         }
555         return NULL;
556 }
557
558 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
559                                                                 int (*cond)(void*), void *data )
560 {
561         struct ast_frame *f;
562
563         while(ms > 0) {
564                 if( cond && ((*cond)(data) == 0 ) )
565                         return 0;
566                 ms = ast_waitfor(chan, ms);
567                 if (ms <0)
568                         return -1;
569                 if (ms > 0) {
570                         f = ast_read(chan);
571                         if (!f)
572                                 return -1;
573                         ast_frfree(f);
574                 }
575         }
576         return 0;
577 }
578
579 int ast_safe_sleep(struct ast_channel *chan, int ms)
580 {
581         struct ast_frame *f;
582         while(ms > 0) {
583                 ms = ast_waitfor(chan, ms);
584                 if (ms <0)
585                         return -1;
586                 if (ms > 0) {
587                         f = ast_read(chan);
588                         if (!f)
589                                 return -1;
590                         ast_frfree(f);
591                 }
592         }
593         return 0;
594 }
595
596 static void free_cid(struct ast_callerid *cid)
597 {
598         if (cid->cid_dnid)
599                 free(cid->cid_dnid);
600         if (cid->cid_num)
601                 free(cid->cid_num);     
602         if (cid->cid_name)
603                 free(cid->cid_name);    
604         if (cid->cid_ani)
605                 free(cid->cid_ani);
606         if (cid->cid_rdnis)
607                 free(cid->cid_rdnis);
608 }
609
610 void ast_channel_free(struct ast_channel *chan)
611 {
612         struct ast_channel *last=NULL, *cur;
613         int fd;
614         struct ast_var_t *vardata;
615         struct ast_frame *f, *fp;
616         struct varshead *headp;
617         char name[AST_CHANNEL_NAME];
618         
619         headp=&chan->varshead;
620         
621         ast_mutex_lock(&chlock);
622         cur = channels;
623         while(cur) {
624                 if (cur == chan) {
625                         if (last)
626                                 last->next = cur->next;
627                         else
628                                 channels = cur->next;
629                         break;
630                 }
631                 last = cur;
632                 cur = cur->next;
633         }
634         if (!cur)
635                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
636         else {
637                 /* Lock and unlock the channel just to be sure nobody
638                    has it locked still */
639                 ast_mutex_lock(&cur->lock);
640                 ast_mutex_unlock(&cur->lock);
641         }
642         if (chan->tech_pvt) {
643                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
644                 free(chan->tech_pvt);
645         }
646
647         strncpy(name, chan->name, sizeof(name)-1);
648         
649         /* Stop monitoring */
650         if (chan->monitor) {
651                 chan->monitor->stop( chan, 0 );
652         }
653
654         /* If there is native format music-on-hold state, free it */
655         if(chan->music_state)
656                 ast_moh_cleanup(chan);
657
658         /* Free translatosr */
659         if (chan->readtrans)
660                 ast_translator_free_path(chan->readtrans);
661         if (chan->writetrans)
662                 ast_translator_free_path(chan->writetrans);
663         if (chan->pbx) 
664                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
665         free_cid(&chan->cid);
666         ast_mutex_destroy(&chan->lock);
667         /* Close pipes if appropriate */
668         if ((fd = chan->alertpipe[0]) > -1)
669                 close(fd);
670         if ((fd = chan->alertpipe[1]) > -1)
671                 close(fd);
672         if ((fd = chan->timingfd) > -1)
673                 close(fd);
674         f = chan->readq;
675         chan->readq = NULL;
676         while(f) {
677                 fp = f;
678                 f = f->next;
679                 ast_frfree(fp);
680         }
681         
682         /* loop over the variables list, freeing all data and deleting list items */
683         /* no need to lock the list, as the channel is already locked */
684         
685         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
686                     vardata = AST_LIST_REMOVE_HEAD(headp, entries);
687 /*                  printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata)); */
688                     ast_var_delete(vardata);
689         }
690
691         free(chan);
692         ast_mutex_unlock(&chlock);
693
694         ast_device_state_changed(name);
695 }
696
697 static void ast_spy_detach(struct ast_channel *chan) 
698 {
699         struct ast_channel_spy *chanspy;
700         int to=3000;
701         int sleepms = 100;
702
703         for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
704                 if (chanspy->status == CHANSPY_RUNNING) {
705                         chanspy->status = CHANSPY_DONE;
706                 }
707         }
708
709         /* signal all the spys to get lost and allow them time to unhook themselves 
710            god help us if they don't......
711         */
712         while (chan->spiers && to >= 0) {
713                 ast_safe_sleep(chan, sleepms);
714                 to -= sleepms;
715         }
716         chan->spiers = NULL;
717         return;
718 }
719
720 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
721 {
722         int res = 0;
723         struct ast_frame f = { AST_FRAME_NULL };
724         if (option_debug)
725                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
726         /* Inform channel driver that we need to be hung up, if it cares */
727         chan->_softhangup |= cause;
728         ast_queue_frame(chan, &f);
729         /* Interrupt any poll call or such */
730         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
731                 pthread_kill(chan->blocker, SIGURG);
732         return res;
733 }
734
735 int ast_softhangup(struct ast_channel *chan, int cause)
736 {
737         int res;
738         ast_mutex_lock(&chan->lock);
739         res = ast_softhangup_nolock(chan, cause);
740         ast_mutex_unlock(&chan->lock);
741         return res;
742 }
743
744 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos) 
745 {
746         struct ast_frame *tmpf = NULL;
747         int count = 0;
748
749         ast_mutex_lock(&spy->lock);
750         for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
751                 count++;
752         }
753         if (count > 1000) {
754                 struct ast_frame *freef, *headf;
755
756                 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.\n");
757                 headf = spy->queue[pos];
758                 /* deref the queue right away so it looks empty */
759                 spy->queue[pos] = NULL;
760                 tmpf = headf;
761                 /* free the wasted frames */
762                 while (tmpf) {
763                         freef = tmpf;
764                         tmpf = tmpf->next;
765                         ast_frfree(freef);
766                 }
767                 ast_mutex_unlock(&spy->lock);
768                 return;
769         }
770
771         if (tmpf) {
772                 tmpf->next = ast_frdup(f);
773         } else {
774                 spy->queue[pos] = ast_frdup(f);
775         }
776
777         ast_mutex_unlock(&spy->lock);
778 }
779
780 static void free_translation(struct ast_channel *clone)
781 {
782         if (clone->writetrans)
783                 ast_translator_free_path(clone->writetrans);
784         if (clone->readtrans)
785                 ast_translator_free_path(clone->readtrans);
786         clone->writetrans = NULL;
787         clone->readtrans = NULL;
788         clone->rawwriteformat = clone->nativeformats;
789         clone->rawreadformat = clone->nativeformats;
790 }
791
792 int ast_hangup(struct ast_channel *chan)
793 {
794         int res = 0;
795         /* Don't actually hang up a channel that will masquerade as someone else, or
796            if someone is going to masquerade as us */
797         ast_mutex_lock(&chan->lock);
798
799         /* get rid of spies */
800         ast_spy_detach(chan);
801
802         if (chan->masq) {
803                 if (ast_do_masquerade(chan)) 
804                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
805         }
806
807         if (chan->masq) {
808                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
809                 ast_mutex_unlock(&chan->lock);
810                 return 0;
811         }
812         /* If this channel is one which will be masqueraded into something, 
813            mark it as a zombie already, so we know to free it later */
814         if (chan->masqr) {
815                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
816                 ast_mutex_unlock(&chan->lock);
817                 return 0;
818         }
819         free_translation(chan);
820         if (chan->stream) 
821                 ast_closestream(chan->stream);
822         if (chan->vstream)
823                 ast_closestream(chan->vstream);
824         if (chan->sched)
825                 sched_context_destroy(chan->sched);
826         /* Clear any tone stuff remaining */
827         if (chan->generatordata)
828                 chan->generator->release(chan, chan->generatordata);
829         chan->generatordata = NULL;
830         chan->generator = NULL;
831         if (chan->cdr) {
832                 /* End the CDR if it hasn't already */
833                 ast_cdr_end(chan->cdr);
834                 /* Post and Free the CDR */
835                 ast_cdr_post(chan->cdr);
836                 ast_cdr_free(chan->cdr);
837         }
838         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
839                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
840                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
841                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
842                 CRASH;
843         }
844         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
845                 if (option_debug)
846                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
847                 if (chan->tech->hangup)
848                         res = chan->tech->hangup(chan);
849         } else
850                 if (option_debug)
851                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
852                         
853         ast_mutex_unlock(&chan->lock);
854         manager_event(EVENT_FLAG_CALL, "Hangup", 
855                         "Channel: %s\r\n"
856                         "Uniqueid: %s\r\n"
857                         "Cause: %i\r\n",
858                         chan->name, chan->uniqueid, chan->hangupcause);
859         ast_channel_free(chan);
860         return res;
861 }
862
863 void ast_channel_unregister(const struct ast_channel_tech *tech)
864 {
865         struct chanlist *chan, *last=NULL;
866
867         if (option_debug)
868                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", tech->type);
869
870         ast_mutex_lock(&chlock);
871
872         chan = backends;
873         while (chan) {
874                 if (chan->tech == tech) {
875                         if (last)
876                                 last->next = chan->next;
877                         else
878                                 backends = backends->next;
879                         free(chan);
880                         ast_mutex_unlock(&chlock);
881
882                         if (option_verbose > 1)
883                                 ast_verbose( VERBOSE_PREFIX_2 "Unregistered channel type '%s'\n", tech->type);
884
885                         return;
886                 }
887                 last = chan;
888                 chan = chan->next;
889         }
890
891         ast_mutex_unlock(&chlock);
892 }
893
894 int ast_answer(struct ast_channel *chan)
895 {
896         int res = 0;
897         ast_mutex_lock(&chan->lock);
898         /* Stop if we're a zombie or need a soft hangup */
899         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
900                 ast_mutex_unlock(&chan->lock);
901                 return -1;
902         }
903         switch(chan->_state) {
904         case AST_STATE_RINGING:
905         case AST_STATE_RING:
906                 if (chan->tech->answer)
907                         res = chan->tech->answer(chan);
908                 ast_setstate(chan, AST_STATE_UP);
909                 if (chan->cdr)
910                         ast_cdr_answer(chan->cdr);
911                 ast_mutex_unlock(&chan->lock);
912                 return res;
913                 break;
914         case AST_STATE_UP:
915                 if (chan->cdr)
916                         ast_cdr_answer(chan->cdr);
917                 break;
918         }
919         ast_mutex_unlock(&chan->lock);
920         return 0;
921 }
922
923
924
925 void ast_deactivate_generator(struct ast_channel *chan)
926 {
927         ast_mutex_lock(&chan->lock);
928         if (chan->generatordata) {
929                 if (chan->generator && chan->generator->release) 
930                         chan->generator->release(chan, chan->generatordata);
931                 chan->generatordata = NULL;
932                 chan->generator = NULL;
933                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
934                 ast_settimeout(chan, 0, NULL, NULL);
935         }
936         ast_mutex_unlock(&chan->lock);
937 }
938
939 static int generator_force(void *data)
940 {
941         /* Called if generator doesn't have data */
942         void *tmp;
943         int res;
944         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
945         struct ast_channel *chan = data;
946         tmp = chan->generatordata;
947         chan->generatordata = NULL;
948         generate = chan->generator->generate;
949         res = generate(chan, tmp, 0, 160);
950         chan->generatordata = tmp;
951         if (res) {
952                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
953                 ast_deactivate_generator(chan);
954         }
955         return 0;
956 }
957
958 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
959 {
960         int res = 0;
961         ast_mutex_lock(&chan->lock);
962         if (chan->generatordata) {
963                 if (chan->generator && chan->generator->release)
964                         chan->generator->release(chan, chan->generatordata);
965                 chan->generatordata = NULL;
966         }
967         ast_prod(chan);
968         if ((chan->generatordata = gen->alloc(chan, params))) {
969                 ast_settimeout(chan, 160, generator_force, chan);
970                 chan->generator = gen;
971         } else {
972                 res = -1;
973         }
974         ast_mutex_unlock(&chan->lock);
975         return res;
976 }
977
978 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
979 {
980         /* Wait for x amount of time on a file descriptor to have input.  */
981         struct timeval start, now;
982         int res;
983         int x, y;
984         int winner = -1;
985         int spoint;
986         struct pollfd *pfds;
987         
988         pfds = alloca(sizeof(struct pollfd) * n);
989         if (!pfds) {
990                 ast_log(LOG_ERROR, "Out of memory\n");
991                 return -1;
992         }
993         if (*ms > 0)
994                 gettimeofday(&start, NULL);
995         y = 0;
996         for (x=0;x<n;x++) {
997                 if (fds[x] > -1) {
998                         pfds[y].fd = fds[x];
999                         pfds[y].events = POLLIN | POLLPRI;
1000                         y++;
1001                 }
1002         }
1003         res = poll(pfds, y, *ms);
1004         if (res < 0) {
1005                 /* Simulate a timeout if we were interrupted */
1006                 if (errno != EINTR)
1007                         *ms = -1;
1008                 else
1009                         *ms = 0;
1010                 return -1;
1011         }
1012         spoint = 0;
1013         for (x=0;x<n;x++) {
1014                 if (fds[x] > -1) {
1015                         if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1016                                 winner = fds[x];
1017                                 if (exception) {
1018                                         if (res & POLLPRI)
1019                                                 *exception = -1;
1020                                         else
1021                                                 *exception = 0;
1022                                 }
1023                         }
1024                 }
1025         }
1026         if (*ms > 0) {
1027                 long passed;
1028                 gettimeofday(&now, NULL);
1029                 passed = (now.tv_sec - start.tv_sec) * 1000;
1030                 passed += (now.tv_usec - start.tv_usec) / 1000;
1031                 if (passed <= *ms)
1032                         *ms -= passed;
1033                 else
1034                         *ms = 0;
1035         }
1036         return winner;
1037 }
1038
1039 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
1040         int *exception, int *outfd, int *ms)
1041 {
1042         /* Wait for x amount of time on a file descriptor to have input.  */
1043         struct timeval start, end;
1044         struct pollfd *pfds;
1045         int res;
1046         long rms;
1047         int x, y, max;
1048         int spoint;
1049         time_t now = 0;
1050         long whentohangup = 0, havewhen = 0, diff;
1051         struct ast_channel *winner = NULL;
1052
1053         pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1054         if (!pfds) {
1055                 ast_log(LOG_ERROR, "Out of memory\n");
1056                 *outfd = -1;
1057                 return NULL;
1058         }
1059
1060         if (outfd)
1061                 *outfd = -99999;
1062         if (exception)
1063                 *exception = 0;
1064         
1065         /* Perform any pending masquerades */
1066         for (x=0;x<n;x++) {
1067                 ast_mutex_lock(&c[x]->lock);
1068                 if (c[x]->whentohangup) {
1069                         if (!havewhen)
1070                                 time(&now);
1071                         diff = c[x]->whentohangup - now;
1072                         if (!havewhen || (diff < whentohangup)) {
1073                                 havewhen++;
1074                                 whentohangup = diff;
1075                         }
1076                 }
1077                 if (c[x]->masq) {
1078                         if (ast_do_masquerade(c[x])) {
1079                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1080                                 *ms = -1;
1081                                 ast_mutex_unlock(&c[x]->lock);
1082                                 return NULL;
1083                         }
1084                 }
1085                 ast_mutex_unlock(&c[x]->lock);
1086         }
1087
1088         rms = *ms;
1089         
1090         if (havewhen) {
1091                 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1092                         rms =  whentohangup * 1000;
1093                 }
1094         }
1095         max = 0;
1096         for (x=0;x<n;x++) {
1097                 for (y=0;y<AST_MAX_FDS;y++) {
1098                         if (c[x]->fds[y] > -1) {
1099                                 pfds[max].fd = c[x]->fds[y];
1100                                 pfds[max].events = POLLIN | POLLPRI;
1101                                 max++;
1102                         }
1103                 }
1104                 CHECK_BLOCKING(c[x]);
1105         }
1106         for (x=0;x<nfds; x++) {
1107                 if (fds[x] > -1) {
1108                         pfds[max].fd = fds[x];
1109                         pfds[max].events = POLLIN | POLLPRI;
1110                         max++;
1111                 }
1112         }
1113         if (*ms > 0) 
1114                 gettimeofday(&start, NULL);
1115         res = poll(pfds, max, rms);
1116         if (res < 0) {
1117                 for (x=0;x<n;x++) 
1118                         ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1119                 /* Simulate a timeout if we were interrupted */
1120                 if (errno != EINTR)
1121                         *ms = -1;
1122                 else {
1123                         /* Just an interrupt */
1124 #if 0
1125                         *ms = 0;
1126 #endif                  
1127                 }
1128                 return NULL;
1129         } else {
1130                 /* If no fds signalled, then timeout. So set ms = 0
1131                    since we may not have an exact timeout.
1132                 */
1133                 if (res == 0)
1134                         *ms = 0;
1135         }
1136
1137         if (havewhen)
1138                 time(&now);
1139         spoint = 0;
1140         for (x=0;x<n;x++) {
1141                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1142                 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1143                         c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1144                         if (!winner)
1145                                 winner = c[x];
1146                 }
1147                 for (y=0;y<AST_MAX_FDS;y++) {
1148                         if (c[x]->fds[y] > -1) {
1149                                 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1150                                         if (res & POLLPRI)
1151                                                 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1152                                         else
1153                                                 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1154                                         c[x]->fdno = y;
1155                                         winner = c[x];
1156                                 }
1157                         }
1158                 }
1159         }
1160         for (x=0;x<nfds;x++) {
1161                 if (fds[x] > -1) {
1162                         if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1163                                 if (outfd)
1164                                         *outfd = fds[x];
1165                                 if (exception) {        
1166                                         if (res & POLLPRI) 
1167                                                 *exception = -1;
1168                                         else
1169                                                 *exception = 0;
1170                                 }
1171                                 winner = NULL;
1172                         }
1173                 }       
1174         }
1175         if (*ms > 0) {
1176                 long diff;
1177                 gettimeofday(&end, NULL);
1178                 diff = (end.tv_sec - start.tv_sec) * 1000;
1179                 diff += (end.tv_usec - start.tv_usec) / 1000;
1180                 if (diff < *ms)
1181                         *ms -= diff;
1182                 else
1183                         *ms = 0;
1184         }
1185         return winner;
1186 }
1187
1188 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1189 {
1190         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1191 }
1192
1193 int ast_waitfor(struct ast_channel *c, int ms)
1194 {
1195         struct ast_channel *chan;
1196         int oldms = ms;
1197         chan = ast_waitfor_n(&c, 1, &ms);
1198         if (ms < 0) {
1199                 if (oldms < 0)
1200                         return 0;
1201                 else
1202                         return -1;
1203         }
1204         return ms;
1205 }
1206
1207 char ast_waitfordigit(struct ast_channel *c, int ms)
1208 {
1209         /* XXX Should I be merged with waitfordigit_full XXX */
1210         struct ast_frame *f;
1211         char result = 0;
1212         /* Stop if we're a zombie or need a soft hangup */
1213         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1214                 return -1;
1215         /* Wait for a digit, no more than ms milliseconds total. */
1216         while(ms && !result) {
1217                 ms = ast_waitfor(c, ms);
1218                 if (ms < 0) /* Error */
1219                         result = -1; 
1220                 else if (ms > 0) {
1221                         /* Read something */
1222                         f = ast_read(c);
1223                         if (f) {
1224                                 if (f->frametype == AST_FRAME_DTMF) 
1225                                         result = f->subclass;
1226                                 ast_frfree(f);
1227                         } else
1228                                 result = -1;
1229                 }
1230         }
1231         return result;
1232 }
1233
1234 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1235 {
1236         int res = -1;
1237 #ifdef ZAPTEL_OPTIMIZATIONS
1238         if (c->timingfd > -1) {
1239                 if (!func) {
1240                         samples = 0;
1241                         data = 0;
1242                 }
1243                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1244                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1245                 c->timingfunc = func;
1246                 c->timingdata = data;
1247         }
1248 #endif  
1249         return res;
1250 }
1251 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1252 {
1253         struct ast_frame *f;
1254         struct ast_channel *rchan;
1255         int outfd;
1256         int res;
1257         /* Stop if we're a zombie or need a soft hangup */
1258         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1259                 return -1;
1260         /* Wait for a digit, no more than ms milliseconds total. */
1261         while(ms) {
1262                 errno = 0;
1263                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1264                 if ((!rchan) && (outfd < 0) && (ms)) { 
1265                         if (errno == 0 || errno == EINTR)
1266                                 continue;
1267                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1268                         return -1;
1269                 } else if (outfd > -1) {
1270                         /* The FD we were watching has something waiting */
1271                         return 1;
1272                 } else if (rchan) {
1273                         f = ast_read(c);
1274                         if(!f) {
1275                                 return -1;
1276                         }
1277
1278                         switch(f->frametype) {
1279                         case AST_FRAME_DTMF:
1280                                 res = f->subclass;
1281                                 ast_frfree(f);
1282                                 return res;
1283                         case AST_FRAME_CONTROL:
1284                                 switch(f->subclass) {
1285                                 case AST_CONTROL_HANGUP:
1286                                         ast_frfree(f);
1287                                         return -1;
1288                                 case AST_CONTROL_RINGING:
1289                                 case AST_CONTROL_ANSWER:
1290                                         /* Unimportant */
1291                                         break;
1292                                 default:
1293                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1294                                 }
1295                         case AST_FRAME_VOICE:
1296                                 /* Write audio if appropriate */
1297                                 if (audiofd > -1)
1298                                         write(audiofd, f->data, f->datalen);
1299                         }
1300                         /* Ignore */
1301                         ast_frfree(f);
1302                 }
1303         }
1304         return 0; /* Time is up */
1305 }
1306
1307 struct ast_frame *ast_read(struct ast_channel *chan)
1308 {
1309         struct ast_frame *f = NULL;
1310         int blah;
1311         int prestate;
1312 #ifdef ZAPTEL_OPTIMIZATIONS
1313         int (*func)(void *);
1314         void *data;
1315         int res;
1316 #endif
1317         static struct ast_frame null_frame = 
1318         {
1319                 AST_FRAME_NULL,
1320         };
1321         
1322         ast_mutex_lock(&chan->lock);
1323         if (chan->masq) {
1324                 if (ast_do_masquerade(chan)) {
1325                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1326                         f = NULL;
1327                 } else
1328                         f =  &null_frame;
1329                 ast_mutex_unlock(&chan->lock);
1330                 return f;
1331         }
1332
1333         /* Stop if we're a zombie or need a soft hangup */
1334         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1335                 if (chan->generator)
1336                         ast_deactivate_generator(chan);
1337                 ast_mutex_unlock(&chan->lock);
1338                 return NULL;
1339         }
1340         prestate = chan->_state;
1341
1342         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1343                 /* We have DTMF that has been deferred.  Return it now */
1344                 chan->dtmff.frametype = AST_FRAME_DTMF;
1345                 chan->dtmff.subclass = chan->dtmfq[0];
1346                 /* Drop first digit */
1347                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1348                 ast_mutex_unlock(&chan->lock);
1349                 return &chan->dtmff;
1350         }
1351         
1352         /* Read and ignore anything on the alertpipe, but read only
1353            one sizeof(blah) per frame that we send from it */
1354         if (chan->alertpipe[0] > -1) {
1355                 read(chan->alertpipe[0], &blah, sizeof(blah));
1356         }
1357 #ifdef ZAPTEL_OPTIMIZATIONS
1358         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1359                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1360                 blah = -1;
1361                 /* IF we can't get event, assume it's an expired as-per the old interface */
1362                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1363                 if (res) 
1364                         blah = ZT_EVENT_TIMER_EXPIRED;
1365
1366                 if (blah == ZT_EVENT_TIMER_PING) {
1367 #if 0
1368                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1369 #endif                  
1370                         if (!chan->readq || !chan->readq->next) {
1371                                 /* Acknowledge PONG unless we need it again */
1372 #if 0
1373                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1374 #endif                          
1375                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1376                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1377                                 }
1378                         }
1379                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1380                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1381                         func = chan->timingfunc;
1382                         data = chan->timingdata;
1383                         ast_mutex_unlock(&chan->lock);
1384                         if (func) {
1385 #if 0
1386                                 ast_log(LOG_DEBUG, "Calling private function\n");
1387 #endif                  
1388                                 func(data);
1389                         } else {
1390                                 blah = 0;
1391                                 ast_mutex_lock(&chan->lock);
1392                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1393                                 chan->timingdata = NULL;
1394                                 ast_mutex_unlock(&chan->lock);
1395                         }
1396                         f =  &null_frame;
1397                         return f;
1398                 } else
1399                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1400         }
1401 #endif
1402         /* Check for pending read queue */
1403         if (chan->readq) {
1404                 f = chan->readq;
1405                 chan->readq = f->next;
1406                 /* Interpret hangup and return NULL */
1407                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1408                         ast_frfree(f);
1409                         f = NULL;
1410                 }
1411         } else {
1412                 chan->blocker = pthread_self();
1413                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1414                         if (chan->tech->exception) 
1415                                 f = chan->tech->exception(chan);
1416                         else {
1417                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1418                                 f = &null_frame;
1419                         }
1420                         /* Clear the exception flag */
1421                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1422                 } else
1423                 if (chan->tech->read)
1424                         f = chan->tech->read(chan);
1425                 else
1426                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1427         }
1428
1429
1430         if (f && (f->frametype == AST_FRAME_VOICE)) {
1431                 if (!(f->subclass & chan->nativeformats)) {
1432                         /* This frame can't be from the current native formats -- drop it on the
1433                            floor */
1434                         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));
1435                         ast_frfree(f);
1436                         f = &null_frame;
1437                 } else {
1438                         if (chan->spiers) {
1439                                 struct ast_channel_spy *spying;
1440                                 for (spying = chan->spiers; spying; spying=spying->next) {
1441                                         ast_queue_spy_frame(spying, f, 0);
1442                                 }
1443                         }
1444                         if (chan->monitor && chan->monitor->read_stream ) {
1445 #ifndef MONITOR_CONSTANT_DELAY
1446                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1447                                 if (jump >= 0) {
1448                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1449                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1450                                         chan->insmpl += jump + 2 * f->samples;
1451                                 } else
1452                                         chan->insmpl+= f->samples;
1453 #else
1454                                 int jump = chan->outsmpl - chan->insmpl;
1455                                 if (jump - MONITOR_DELAY >= 0) {
1456                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1457                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1458                                         chan->insmpl += jump;
1459                                 } else
1460                                         chan->insmpl += f->samples;
1461 #endif
1462                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1463                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1464                         }
1465                         if (chan->readtrans) {
1466                                 f = ast_translate(chan->readtrans, f, 1);
1467                                 if (!f)
1468                                         f = &null_frame;
1469                         }
1470                 }
1471         }
1472
1473         /* Make sure we always return NULL in the future */
1474         if (!f) {
1475                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1476                 if (chan->generator)
1477                         ast_deactivate_generator(chan);
1478                 /* End the CDR if appropriate */
1479                 if (chan->cdr)
1480                         ast_cdr_end(chan->cdr);
1481         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1482                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1483                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1484                 else
1485                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1486                 f = &null_frame;
1487         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1488                 if (prestate == AST_STATE_UP) {
1489                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1490                         f = &null_frame;
1491                 }
1492                 /* Answer the CDR */
1493                 ast_setstate(chan, AST_STATE_UP);
1494                 ast_cdr_answer(chan->cdr);
1495         } 
1496
1497         /* Run any generator sitting on the line */
1498         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1499                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1500                    will be calling the generator instead */
1501                 void *tmp;
1502                 int res;
1503                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1504                 if (chan->timingfunc) {
1505                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1506                         ast_settimeout(chan, 0, NULL, NULL);
1507                 }
1508                 tmp = chan->generatordata;
1509                 chan->generatordata = NULL;
1510                 generate = chan->generator->generate;
1511                 res = generate(chan, tmp, f->datalen, f->samples);
1512                 chan->generatordata = tmp;
1513                 if (res) {
1514                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1515                         ast_deactivate_generator(chan);
1516                 }
1517         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1518                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1519                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1520                         ast_settimeout(chan, 160, generator_force, chan);
1521                 }
1522         }
1523         if (chan->fin & 0x80000000)
1524                 ast_frame_dump(chan->name, f, "<<");
1525         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1526                 chan->fin &= 0x80000000;
1527         else
1528                 chan->fin++;
1529         ast_mutex_unlock(&chan->lock);
1530         return f;
1531 }
1532
1533 int ast_indicate(struct ast_channel *chan, int condition)
1534 {
1535         int res = -1;
1536         /* Stop if we're a zombie or need a soft hangup */
1537         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1538                 return -1;
1539         ast_mutex_lock(&chan->lock);
1540         if (chan->tech->indicate)
1541                 res = chan->tech->indicate(chan, condition);
1542         ast_mutex_unlock(&chan->lock);
1543         if (!chan->tech->indicate || res) {
1544                 /*
1545                  * Device does not support (that) indication, lets fake
1546                  * it by doing our own tone generation. (PM2002)
1547                  */
1548                 if (condition >= 0) {
1549                         const struct tone_zone_sound *ts = NULL;
1550                         switch (condition) {
1551                          case AST_CONTROL_RINGING:
1552                                 ts = ast_get_indication_tone(chan->zone, "ring");
1553                                 break;
1554                          case AST_CONTROL_BUSY:
1555                                 ts = ast_get_indication_tone(chan->zone, "busy");
1556                                 break;
1557                          case AST_CONTROL_CONGESTION:
1558                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1559                                 break;
1560                         }
1561                         if (ts && ts->data[0]) {
1562                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1563                                 ast_playtones_start(chan,0,ts->data, 1);
1564                                 res = 0;
1565                         } else if (condition == AST_CONTROL_PROGRESS) {
1566                                 /* ast_playtones_stop(chan); */
1567                         } else if (condition == AST_CONTROL_PROCEEDING) {
1568                                 /* Do nothing, really */
1569                         } else if (condition == AST_CONTROL_HOLD) {
1570                                 /* Do nothing.... */
1571                         } else if (condition == AST_CONTROL_UNHOLD) {
1572                                 /* Do nothing.... */
1573                         } else {
1574                                 /* not handled */
1575                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1576                                 res = -1;
1577                         }
1578                 }
1579                 else ast_playtones_stop(chan);
1580         }
1581         return res;
1582 }
1583
1584 int ast_recvchar(struct ast_channel *chan, int timeout)
1585 {
1586         int res,ourto,c;
1587         struct ast_frame *f;
1588         
1589         ourto = timeout;
1590         for(;;)
1591            {
1592                 if (ast_check_hangup(chan)) return -1;
1593                 res = ast_waitfor(chan,ourto);
1594                 if (res <= 0) /* if timeout */
1595                    {
1596                         return 0;
1597                    }
1598                 ourto = res;
1599                 f = ast_read(chan);
1600                 if (f == NULL) return -1; /* if hangup */
1601                 if ((f->frametype == AST_FRAME_CONTROL) &&
1602                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1603                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1604                    {
1605                         c = *((char *)f->data);  /* get the data */
1606                         ast_frfree(f);
1607                         return(c);
1608                    }
1609                 ast_frfree(f);
1610         }
1611 }
1612
1613 int ast_sendtext(struct ast_channel *chan, char *text)
1614 {
1615         int res = 0;
1616         /* Stop if we're a zombie or need a soft hangup */
1617         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1618                 return -1;
1619         CHECK_BLOCKING(chan);
1620         if (chan->tech->send_text)
1621                 res = chan->tech->send_text(chan, text);
1622         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1623         return res;
1624 }
1625
1626 static int do_senddigit(struct ast_channel *chan, char digit)
1627 {
1628         int res = -1;
1629
1630         if (chan->tech->send_digit)
1631                 res = chan->tech->send_digit(chan, digit);
1632         if (!chan->tech->send_digit || res) {
1633                 /*
1634                  * Device does not support DTMF tones, lets fake
1635                  * it by doing our own generation. (PM2002)
1636                  */
1637                 static const char* dtmf_tones[] = {
1638                         "!941+1336/100,!0/100", /* 0 */
1639                         "!697+1209/100,!0/100", /* 1 */
1640                         "!697+1336/100,!0/100", /* 2 */
1641                         "!697+1477/100,!0/100", /* 3 */
1642                         "!770+1209/100,!0/100", /* 4 */
1643                         "!770+1336/100,!0/100", /* 5 */
1644                         "!770+1477/100,!0/100", /* 6 */
1645                         "!852+1209/100,!0/100", /* 7 */
1646                         "!852+1336/100,!0/100", /* 8 */
1647                         "!852+1477/100,!0/100", /* 9 */
1648                         "!697+1633/100,!0/100", /* A */
1649                         "!770+1633/100,!0/100", /* B */
1650                         "!852+1633/100,!0/100", /* C */
1651                         "!941+1633/100,!0/100", /* D */
1652                         "!941+1209/100,!0/100", /* * */
1653                         "!941+1477/100,!0/100" };       /* # */
1654                 if (digit >= '0' && digit <='9')
1655                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1656                 else if (digit >= 'A' && digit <= 'D')
1657                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1658                 else if (digit == '*')
1659                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1660                 else if (digit == '#')
1661                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1662                 else {
1663                         /* not handled */
1664                         ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1665                 }
1666         }
1667         return 0;
1668 }
1669
1670 int ast_senddigit(struct ast_channel *chan, char digit)
1671 {
1672         return do_senddigit(chan, digit);
1673 }
1674
1675 int ast_prod(struct ast_channel *chan)
1676 {
1677         struct ast_frame a = { AST_FRAME_VOICE };
1678         char nothing[128];
1679         /* Send an empty audio frame to get things moving */
1680         if (chan->_state != AST_STATE_UP) {
1681                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1682                 a.subclass = chan->rawwriteformat;
1683                 a.data = nothing + AST_FRIENDLY_OFFSET;
1684                 a.src = "ast_prod";
1685                 if (ast_write(chan, &a))
1686                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1687         }
1688         return 0;
1689 }
1690
1691 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1692 {
1693         int res;
1694         if (!chan->tech->write_video)
1695                 return 0;
1696         res = ast_write(chan, fr);
1697         if (!res)
1698                 res = 1;
1699         return res;
1700 }
1701
1702 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1703 {
1704         int res = -1;
1705         struct ast_frame *f = NULL;
1706         /* Stop if we're a zombie or need a soft hangup */
1707         ast_mutex_lock(&chan->lock);
1708         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1709                 ast_mutex_unlock(&chan->lock);
1710                 return -1;
1711         }
1712         /* Handle any pending masquerades */
1713         if (chan->masq) {
1714                 if (ast_do_masquerade(chan)) {
1715                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1716                         ast_mutex_unlock(&chan->lock);
1717                         return -1;
1718                 }
1719         }
1720         if (chan->masqr) {
1721                 ast_mutex_unlock(&chan->lock);
1722                 return 0;
1723         }
1724         if (chan->generatordata) {
1725                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1726                         ast_deactivate_generator(chan);
1727                 else {
1728                         ast_mutex_unlock(&chan->lock);
1729                         return 0;
1730                 }
1731         }
1732         if (chan->fout & 0x80000000)
1733                 ast_frame_dump(chan->name, fr, ">>");
1734         CHECK_BLOCKING(chan);
1735         switch(fr->frametype) {
1736         case AST_FRAME_CONTROL:
1737                 /* XXX Interpret control frames XXX */
1738                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1739                 break;
1740         case AST_FRAME_DTMF:
1741                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1742                 ast_mutex_unlock(&chan->lock);
1743                 res = do_senddigit(chan,fr->subclass);
1744                 ast_mutex_lock(&chan->lock);
1745                 CHECK_BLOCKING(chan);
1746                 break;
1747         case AST_FRAME_TEXT:
1748                 if (chan->tech->send_text)
1749                         res = chan->tech->send_text(chan, (char *) fr->data);
1750                 else
1751                         res = 0;
1752                 break;
1753         case AST_FRAME_HTML:
1754                 if (chan->tech->send_html)
1755                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1756                 else
1757                         res = 0;
1758                 break;
1759         case AST_FRAME_VIDEO:
1760                 /* XXX Handle translation of video codecs one day XXX */
1761                 if (chan->tech->write_video)
1762                         res = chan->tech->write_video(chan, fr);
1763                 else
1764                         res = 0;
1765                 break;
1766         default:
1767                 if (chan->tech->write) {
1768                         if (chan->writetrans) {
1769                                 f = ast_translate(chan->writetrans, fr, 0);
1770                         } else
1771                                 f = fr;
1772                         if (f) {
1773                                 res = chan->tech->write(chan, f);
1774
1775                                 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
1776                                         struct ast_channel_spy *spying;
1777                                         for (spying = chan->spiers; spying; spying=spying->next) {
1778                                                 ast_queue_spy_frame(spying, f, 1);
1779                                         }
1780                                 }
1781
1782                                 if( chan->monitor &&
1783                                                 chan->monitor->write_stream &&
1784                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1785 #ifndef MONITOR_CONSTANT_DELAY
1786                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1787                                         if (jump >= 0) {
1788                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1789                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1790                                                 chan->outsmpl += jump + 2 * f->samples;
1791                                         } else
1792                                                 chan->outsmpl += f->samples;
1793 #else
1794                                         int jump = chan->insmpl - chan->outsmpl;
1795                                         if (jump - MONITOR_DELAY >= 0) {
1796                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1797                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1798                                                 chan->outsmpl += jump;
1799                                         } else
1800                                                 chan->outsmpl += f->samples;
1801 #endif
1802                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1803                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1804                                 }
1805                         } else
1806                                 res = 0;
1807                 }
1808         }
1809         if (f && (f != fr))
1810                 ast_frfree(f);
1811         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1812         /* Consider a write failure to force a soft hangup */
1813         if (res < 0)
1814                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1815         else {
1816                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1817                         chan->fout &= 0x80000000;
1818                 else
1819                         chan->fout++;
1820                 chan->fout++;
1821         }
1822         ast_mutex_unlock(&chan->lock);
1823         return res;
1824 }
1825
1826 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
1827                       struct ast_trans_pvt **trans, const int direction)
1828 {
1829         int native;
1830         int res;
1831         
1832         native = chan->nativeformats;
1833         /* Find a translation path from the native format to one of the desired formats */
1834         if (!direction)
1835                 /* reading */
1836                 res = ast_translator_best_choice(&fmt, &native);
1837         else
1838                 /* writing */
1839                 res = ast_translator_best_choice(&native, &fmt);
1840
1841         if (res < 0) {
1842                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1843                         ast_getformatname(native), ast_getformatname(fmt));
1844                 return -1;
1845         }
1846         
1847         /* Now we have a good choice for both. */
1848         ast_mutex_lock(&chan->lock);
1849         *rawformat = native;
1850         /* User perspective is fmt */
1851         *format = fmt;
1852         /* Free any read translation we have right now */
1853         if (*trans)
1854                 ast_translator_free_path(*trans);
1855         /* Build a translation path from the raw format to the desired format */
1856         if (!direction)
1857                 /* reading */
1858                 *trans = ast_translator_build_path(*format, *rawformat);
1859         else
1860                 /* writing */
1861                 *trans = ast_translator_build_path(*rawformat, *format);
1862         ast_mutex_unlock(&chan->lock);
1863         if (option_debug)
1864                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
1865                         direction ? "write" : "read", ast_getformatname(fmt));
1866         return 0;
1867 }
1868
1869 int ast_set_read_format(struct ast_channel *chan, int fmt)
1870 {
1871         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
1872                           &chan->readtrans, 0);
1873 }
1874
1875 int ast_set_write_format(struct ast_channel *chan, int fmt)
1876 {
1877         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
1878                           &chan->writetrans, 1);
1879 }
1880
1881 struct ast_channel *__ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cid_num, const char *cid_name, struct outgoing_helper *oh)
1882 {
1883         int state = 0;
1884         int cause = 0;
1885         struct ast_channel *chan;
1886         struct ast_frame *f;
1887         int res = 0;
1888         char *variable;
1889         chan = ast_request(type, format, data, &cause);
1890         if (chan) {
1891                 if (oh) {
1892                         char *tmp, *var;
1893                         /* JDG chanvar */
1894                         if (oh->variable)
1895                                 variable = ast_strdupa(oh->variable);
1896                         else
1897                                 variable = NULL;
1898                         tmp = variable;
1899                         /* FIXME replace this call with strsep  NOT*/
1900                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1901                                 pbx_builtin_setvar( chan, var );
1902                         } /* /JDG */
1903                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1904                         if (oh->account && *oh->account)
1905                                 ast_cdr_setaccount(chan, oh->account);
1906                 }
1907                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1908
1909                 if (!ast_call(chan, data, 0)) {
1910                         while(timeout && (chan->_state != AST_STATE_UP)) {
1911                                 res = ast_waitfor(chan, timeout);
1912                                 if (res < 0) {
1913                                         /* Something not cool, or timed out */
1914                                         break;
1915                                 }
1916                                 /* If done, break out */
1917                                 if (!res)
1918                                         break;
1919                                 if (timeout > -1)
1920                                         timeout = res;
1921                                 f = ast_read(chan);
1922                                 if (!f) {
1923                                         state = AST_CONTROL_HANGUP;
1924                                         res = 0;
1925                                         break;
1926                                 }
1927                                 if (f->frametype == AST_FRAME_CONTROL) {
1928                                         if (f->subclass == AST_CONTROL_RINGING)
1929                                                 state = AST_CONTROL_RINGING;
1930                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1931                                                 state = f->subclass;
1932                                                 ast_frfree(f);
1933                                                 break;
1934                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1935                                                 state = f->subclass;
1936                                                 ast_frfree(f);
1937                                                 break;
1938                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
1939                                                 /* Ignore */
1940                                         } else if (f->subclass == -1) {
1941                                                 /* Ignore -- just stopping indications */
1942                                         } else {
1943                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1944                                         }
1945                                 }
1946                                 ast_frfree(f);
1947                         }
1948                 } else
1949                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1950         } else {
1951                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1952                 switch(cause) {
1953                 case AST_CAUSE_BUSY:
1954                         state = AST_CONTROL_BUSY;
1955                         break;
1956                 case AST_CAUSE_CONGESTION:
1957                         state = AST_CONTROL_CONGESTION;
1958                         break;
1959                 }
1960         }
1961         if (chan) {
1962                 /* Final fixups */
1963                 if (oh) {
1964                         if (oh->context && *oh->context)
1965                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1966                         if (oh->exten && *oh->exten)
1967                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1968                         chan->priority = oh->priority;
1969                 }
1970                 if (chan->_state == AST_STATE_UP) 
1971                         state = AST_CONTROL_ANSWER;
1972         }
1973         if (outstate)
1974                 *outstate = state;
1975         if (chan && res <= 0) {
1976                 if (!chan->cdr) {
1977                         chan->cdr = ast_cdr_alloc();
1978                         if (chan->cdr)
1979                                 ast_cdr_init(chan->cdr, chan);
1980                 }
1981                 if (chan->cdr) {
1982                         char tmp[256];
1983                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
1984                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1985                         ast_cdr_update(chan);
1986                         ast_cdr_start(chan->cdr);
1987                         ast_cdr_end(chan->cdr);
1988                         /* If the cause wasn't handled properly */
1989                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1990                                 ast_cdr_failed(chan->cdr);
1991                 } else 
1992                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1993                 ast_hangup(chan);
1994                 chan = NULL;
1995         }
1996         return chan;
1997 }
1998
1999 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2000 {
2001         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2002 }
2003
2004 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2005 {
2006         struct chanlist *chan;
2007         struct ast_channel *c = NULL;
2008         int capabilities;
2009         int fmt;
2010         int res;
2011         int foo;
2012         if (!cause)
2013                 cause = &foo;
2014         *cause = AST_CAUSE_NOTDEFINED;
2015         if (ast_mutex_lock(&chlock)) {
2016                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2017                 return NULL;
2018         }
2019         chan = backends;
2020         while(chan) {
2021                 if (!strcasecmp(type, chan->tech->type)) {
2022                         capabilities = chan->tech->capabilities;
2023                         fmt = format;
2024                         res = ast_translator_best_choice(&fmt, &capabilities);
2025                         if (res < 0) {
2026                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2027                                 ast_mutex_unlock(&chlock);
2028                                 return NULL;
2029                         }
2030                         ast_mutex_unlock(&chlock);
2031                         if (chan->tech->requester)
2032                                 c = chan->tech->requester(type, capabilities, data, cause);
2033                         if (c) {
2034                                 if (c->_state == AST_STATE_DOWN) {
2035                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2036                                         "Channel: %s\r\n"
2037                                         "State: %s\r\n"
2038                                         "CallerID: %s\r\n"
2039                                         "CallerIDName: %s\r\n"
2040                                         "Uniqueid: %s\r\n",
2041                                         c->name, ast_state2str(c->_state), c->cid.cid_num ? c->cid.cid_num : "<unknown>", c->cid.cid_name ? c->cid.cid_name : "<unknown>",c->uniqueid);
2042                                 }
2043                         }
2044                         return c;
2045                 }
2046                 chan = chan->next;
2047         }
2048         if (!chan) {
2049                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2050                 *cause = AST_CAUSE_NOSUCHDRIVER;
2051         }
2052         ast_mutex_unlock(&chlock);
2053         return c;
2054 }
2055
2056 int ast_parse_device_state(char *device)
2057 {
2058         char name[AST_CHANNEL_NAME] = "";
2059         char *cut;
2060         struct ast_channel *chan;
2061
2062         chan = ast_channel_walk_locked(NULL);
2063         while (chan) {
2064                 strncpy(name, chan->name, sizeof(name)-1);
2065                 ast_mutex_unlock(&chan->lock);
2066                 cut = strchr(name,'-');
2067                 if (cut)
2068                         *cut = 0;
2069                 if (!strcmp(name, device))
2070                         return AST_DEVICE_INUSE;
2071                 chan = ast_channel_walk_locked(chan);
2072         }
2073         return AST_DEVICE_UNKNOWN;
2074 }
2075
2076 int ast_device_state(char *device)
2077 {
2078         char tech[AST_MAX_EXTENSION] = "";
2079         char *number;
2080         struct chanlist *chanls;
2081         int res = 0;
2082         
2083         strncpy(tech, device, sizeof(tech)-1);
2084         number = strchr(tech, '/');
2085         if (!number) {
2086             return AST_DEVICE_INVALID;
2087         }
2088         *number = 0;
2089         number++;
2090                 
2091         if (ast_mutex_lock(&chlock)) {
2092                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2093                 return -1;
2094         }
2095         chanls = backends;
2096         while(chanls) {
2097                 if (!strcasecmp(tech, chanls->tech->type)) {
2098                         ast_mutex_unlock(&chlock);
2099                         if (!chanls->tech->devicestate) 
2100                                 return ast_parse_device_state(device);
2101                         else {
2102                                 res = chanls->tech->devicestate(number);
2103                                 if (res == AST_DEVICE_UNKNOWN)
2104                                         return ast_parse_device_state(device);
2105                                 else
2106                                         return res;
2107                         }
2108                 }
2109                 chanls = chanls->next;
2110         }
2111         ast_mutex_unlock(&chlock);
2112         return AST_DEVICE_INVALID;
2113 }
2114
2115 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2116 {
2117         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2118            If the remote end does not answer within the timeout, then do NOT hang up, but 
2119            return anyway.  */
2120         int res = -1;
2121         /* Stop if we're a zombie or need a soft hangup */
2122         ast_mutex_lock(&chan->lock);
2123         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2124                 if (chan->tech->call)
2125                         res = chan->tech->call(chan, addr, timeout);
2126         ast_mutex_unlock(&chan->lock);
2127         return res;
2128 }
2129
2130 int ast_transfer(struct ast_channel *chan, char *dest) 
2131 {
2132         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2133            If the remote end does not answer within the timeout, then do NOT hang up, but 
2134            return anyway.  */
2135         int res = -1;
2136         /* Stop if we're a zombie or need a soft hangup */
2137         ast_mutex_lock(&chan->lock);
2138         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2139                 if (chan->tech->transfer) {
2140                         res = chan->tech->transfer(chan, dest);
2141                         if (!res)
2142                                 res = 1;
2143                 } else
2144                         res = 0;
2145         }
2146         ast_mutex_unlock(&chan->lock);
2147         return res;
2148 }
2149
2150 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2151 {
2152         int pos=0;
2153         int to = ftimeout;
2154         char d;
2155         /* XXX Merge with full version? XXX */
2156         /* Stop if we're a zombie or need a soft hangup */
2157         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2158                 return -1;
2159         if (!len)
2160                 return -1;
2161         do {
2162                 if (c->stream) {
2163                         d = ast_waitstream(c, AST_DIGIT_ANY);
2164                         ast_stopstream(c);
2165                         usleep(1000);
2166                         if (!d)
2167                                 d = ast_waitfordigit(c, to);
2168                 } else {
2169                         d = ast_waitfordigit(c, to);
2170                 }
2171                 if (d < 0)
2172                         return -1;
2173                 if (d == 0) {
2174                         s[pos]='\0';
2175                         return 1;
2176                 }
2177                 if (!strchr(enders, d))
2178                         s[pos++] = d;
2179                 if (strchr(enders, d) || (pos >= len)) {
2180                         s[pos]='\0';
2181                         return 0;
2182                 }
2183                 to = timeout;
2184         } while(1);
2185         /* Never reached */
2186         return 0;
2187 }
2188
2189 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2190 {
2191         int pos=0;
2192         int to = ftimeout;
2193         char d;
2194         /* Stop if we're a zombie or need a soft hangup */
2195         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2196                 return -1;
2197         if (!len)
2198                 return -1;
2199         do {
2200                 if (c->stream) {
2201                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2202                         ast_stopstream(c);
2203                         usleep(1000);
2204                         if (!d)
2205                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2206                 } else {
2207                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2208                 }
2209                 if (d < 0)
2210                         return -1;
2211                 if (d == 0) {
2212                         s[pos]='\0';
2213                         return 1;
2214                 }
2215                 if (d == 1) {
2216                         s[pos]='\0';
2217                         return 2;
2218                 }
2219                 if (!strchr(enders, d))
2220                         s[pos++] = d;
2221                 if (strchr(enders, d) || (pos >= len)) {
2222                         s[pos]='\0';
2223                         return 0;
2224                 }
2225                 to = timeout;
2226         } while(1);
2227         /* Never reached */
2228         return 0;
2229 }
2230
2231 int ast_channel_supports_html(struct ast_channel *chan)
2232 {
2233         if (chan->tech->send_html)
2234                 return 1;
2235         return 0;
2236 }
2237
2238 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2239 {
2240         if (chan->tech->send_html)
2241                 return chan->tech->send_html(chan, subclass, data, datalen);
2242         return -1;
2243 }
2244
2245 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2246 {
2247         if (chan->tech->send_html)
2248                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2249         return -1;
2250 }
2251
2252 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2253 {
2254         int src;
2255         int dst;
2256
2257         /* Set up translation from the chan to the peer */
2258         src = chan->nativeformats;
2259         dst = peer->nativeformats;
2260         if (ast_translator_best_choice(&dst, &src) < 0) {
2261                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2262                 return -1;
2263         }
2264         /* if the best path is not 'pass through', then
2265            transcoding is needed; if desired, force transcode path
2266            to use SLINEAR between channels */
2267         if ((src != dst) && option_transcode_slin)
2268                 dst = AST_FORMAT_SLINEAR;
2269         if (ast_set_read_format(chan, dst) < 0) {
2270                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2271                 return -1;
2272         }
2273         if (ast_set_write_format(peer, dst) < 0) {
2274                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2275                 return -1;
2276         }
2277
2278         /* Set up translation from the peer to the chan */
2279         src = peer->nativeformats;
2280         dst = chan->nativeformats;
2281         if (ast_translator_best_choice(&dst, &src) < 0) {
2282                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2283                 return -1;
2284         }
2285         /* if the best path is not 'pass through', then
2286            transcoding is needed; if desired, force transcode path
2287            to use SLINEAR between channels */
2288         if ((src != dst) && option_transcode_slin)
2289                 dst = AST_FORMAT_SLINEAR;
2290         if (ast_set_read_format(peer, dst) < 0) {
2291                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2292                 return -1;
2293         }
2294         if (ast_set_write_format(chan, dst) < 0) {
2295                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2296                 return -1;
2297         }
2298         return 0;
2299 }
2300
2301 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2302 {
2303         struct ast_frame null = { AST_FRAME_NULL, };
2304         int res = -1;
2305         if (original == clone) {
2306                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2307                 return -1;
2308         }
2309         ast_mutex_lock(&original->lock);
2310         while(ast_mutex_trylock(&clone->lock)) {
2311                 ast_mutex_unlock(&original->lock);
2312                 usleep(1);
2313                 ast_mutex_lock(&original->lock);
2314         }
2315         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2316                 clone->name, original->name);
2317         if (original->masq) {
2318                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2319                         original->masq->name, original->name);
2320         } else if (clone->masqr) {
2321                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2322                         clone->name, clone->masqr->name);
2323         } else {
2324                 original->masq = clone;
2325                 clone->masqr = original;
2326                 ast_queue_frame(original, &null);
2327                 ast_queue_frame(clone, &null);
2328                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2329                 res = 0;
2330         }
2331         ast_mutex_unlock(&clone->lock);
2332         ast_mutex_unlock(&original->lock);
2333         return res;
2334 }
2335
2336 void ast_change_name(struct ast_channel *chan, char *newname)
2337 {
2338         char tmp[256];
2339         strncpy(tmp, chan->name, sizeof(tmp) - 1);
2340         strncpy(chan->name, newname, sizeof(chan->name) - 1);
2341         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2342 }
2343
2344 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2345 {
2346         struct ast_var_t *current, *newvar;
2347         char *varname;
2348
2349         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2350                 int vartype = 0;
2351
2352                 varname = ast_var_full_name(current);
2353                 if (!varname)
2354                         continue;
2355
2356                 if (varname[0] == '_') {
2357                         vartype = 1;
2358                         if (varname[1] == '_')
2359                                 vartype = 2;
2360                 }
2361
2362                 switch (vartype) {
2363                 case 1:
2364                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2365                         if (newvar) {
2366                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2367                                 if (option_debug)
2368                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2369                         }
2370                         break;
2371                 case 2:
2372                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2373                         if (newvar) {
2374                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2375                                 if (option_debug)
2376                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2377                         }
2378                         break;
2379                 default:
2380                         if (option_debug)
2381                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2382                         break;
2383                 }
2384         }
2385 }
2386
2387 /* Clone channel variables from 'clone' channel into 'original' channel
2388    All variables except those related to app_groupcount are cloned
2389    Variables are actually _removed_ from 'clone' channel, presumably
2390    because it will subsequently be destroyed.
2391    Assumes locks will be in place on both channels when called.
2392 */
2393    
2394 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2395 {
2396         struct ast_var_t *varptr;
2397
2398         /* we need to remove all app_groupcount related variables from the original
2399            channel before merging in the clone's variables; any groups assigned to the
2400            original channel should be released, only those assigned to the clone
2401            should remain
2402         */
2403
2404         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2405                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2406                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2407                         ast_var_delete(varptr);
2408                 }
2409         }
2410         AST_LIST_TRAVERSE_SAFE_END;
2411
2412         /* Append variables from clone channel into original channel */
2413         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2414         if (AST_LIST_FIRST(&clone->varshead))
2415                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2416 }
2417
2418 /* Assumes channel will be locked when called */
2419 int ast_do_masquerade(struct ast_channel *original)
2420 {
2421         int x,i;
2422         int res=0;
2423         int origstate;
2424         struct ast_frame *cur, *prev;
2425         const struct ast_channel_tech *t;
2426         void *t_pvt;
2427         struct ast_callerid tmpcid;
2428         struct ast_channel *clone = original->masq;
2429         int rformat = original->readformat;
2430         int wformat = original->writeformat;
2431         char newn[100];
2432         char orig[100];
2433         char masqn[100];
2434         char zombn[100];
2435
2436 #if 1
2437         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2438                 clone->name, clone->_state, original->name, original->_state);
2439 #endif
2440         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2441            the clone channel into the original channel.  Start by killing off the original
2442            channel's backend.   I'm not sure we're going to keep this function, because 
2443            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2444
2445         /* We need the clone's lock, too */
2446         ast_mutex_lock(&clone->lock);
2447
2448         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2449
2450         /* Having remembered the original read/write formats, we turn off any translation on either
2451            one */
2452         free_translation(clone);
2453         free_translation(original);
2454
2455
2456         /* Unlink the masquerade */
2457         original->masq = NULL;
2458         clone->masqr = NULL;
2459         
2460         /* Save the original name */
2461         strncpy(orig, original->name, sizeof(orig) - 1);
2462         /* Save the new name */
2463         strncpy(newn, clone->name, sizeof(newn) - 1);
2464         /* Create the masq name */
2465         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2466                 
2467         /* Copy the name from the clone channel */
2468         strncpy(original->name, newn, sizeof(original->name)-1);
2469
2470         /* Mangle the name of the clone channel */
2471         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2472         
2473         /* Notify any managers of the change, first the masq then the other */
2474         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2475         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2476
2477         /* Swap the technlogies */      
2478         t = original->tech;
2479         original->tech = clone->tech;
2480         clone->tech = t;
2481
2482         t_pvt = original->tech_pvt;
2483         original->tech_pvt = clone->tech_pvt;
2484         clone->tech_pvt = t_pvt;
2485
2486         /* Swap the readq's */
2487         cur = original->readq;
2488         original->readq = clone->readq;
2489         clone->readq = cur;
2490
2491         /* Swap the alertpipes */
2492         for (i = 0; i < 2; i++) {
2493                 x = original->alertpipe[i];
2494                 original->alertpipe[i] = clone->alertpipe[i];
2495                 clone->alertpipe[i] = x;
2496         }
2497
2498         /* Swap the raw formats */
2499         x = original->rawreadformat;
2500         original->rawreadformat = clone->rawreadformat;
2501         clone->rawreadformat = x;
2502         x = original->rawwriteformat;
2503         original->rawwriteformat = clone->rawwriteformat;
2504         clone->rawwriteformat = x;
2505
2506         /* Save any pending frames on both sides.  Start by counting
2507          * how many we're going to need... */
2508         prev = NULL;
2509         cur = clone->readq;
2510         x = 0;
2511         while(cur) {
2512                 x++;
2513                 prev = cur;
2514                 cur = cur->next;
2515         }
2516         /* If we had any, prepend them to the ones already in the queue, and 
2517          * load up the alertpipe */
2518         if (prev) {
2519                 prev->next = original->readq;
2520                 original->readq = clone->readq;
2521                 clone->readq = NULL;
2522                 if (original->alertpipe[1] > -1) {
2523                         for (i=0;i<x;i++)
2524                                 write(original->alertpipe[1], &x, sizeof(x));
2525                 }
2526         }
2527         clone->_softhangup = AST_SOFTHANGUP_DEV;
2528
2529
2530         /* And of course, so does our current state.  Note we need not
2531            call ast_setstate since the event manager doesn't really consider
2532            these separate.  We do this early so that the clone has the proper
2533            state of the original channel. */
2534         origstate = original->_state;
2535         original->_state = clone->_state;
2536         clone->_state = origstate;
2537
2538         if (clone->tech->fixup){
2539                 res = clone->tech->fixup(original, clone);
2540                 if (res) 
2541                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2542         }
2543
2544         /* Start by disconnecting the original's physical side */
2545         if (clone->tech->hangup)
2546                 res = clone->tech->hangup(clone);
2547         if (res) {
2548                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2549                 ast_mutex_unlock(&clone->lock);
2550                 return -1;
2551         }
2552         
2553         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2554         /* Mangle the name of the clone channel */
2555         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2556         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2557
2558         /* Update the type. */
2559         original->type = clone->type;
2560         
2561         /* Keep the same language.  */
2562         strncpy(original->language, clone->language, sizeof(original->language));
2563         /* Copy the FD's */
2564         for (x=0;x<AST_MAX_FDS;x++) {
2565                 original->fds[x] = clone->fds[x];
2566         }
2567         clone_variables(original, clone);
2568         clone->varshead.first = NULL;
2569         /* Presense of ADSI capable CPE follows clone */
2570         original->adsicpe = clone->adsicpe;
2571         /* Bridge remains the same */
2572         /* CDR fields remain the same */
2573         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2574         /* Application and data remain the same */
2575         /* Clone exception  becomes real one, as with fdno */
2576         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2577         original->fdno = clone->fdno;
2578         /* Schedule context remains the same */
2579         /* Stream stuff stays the same */
2580         /* Keep the original state.  The fixup code will need to work with it most likely */
2581
2582         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2583            out. */
2584         tmpcid = original->cid;
2585         original->cid = clone->cid;
2586         clone->cid = tmpcid;
2587         
2588         /* Restore original timing file descriptor */
2589         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2590         
2591         /* Our native formats are different now */
2592         original->nativeformats = clone->nativeformats;
2593         
2594         /* Context, extension, priority, app data, jump table,  remain the same */
2595         /* pvt switches.  pbx stays the same, as does next */
2596         
2597         /* Set the write format */
2598         ast_set_write_format(original, wformat);
2599
2600         /* Set the read format */
2601         ast_set_read_format(original, rformat);
2602
2603         /* Copy the music class */
2604         strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2605
2606         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2607
2608         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2609            can fix up everything as best as possible */
2610         if (original->tech->fixup) {
2611                 res = original->tech->fixup(clone, original);
2612                 if (res) {
2613                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2614                                 original->type, original->name);
2615                         ast_mutex_unlock(&clone->lock);
2616                         return -1;
2617                 }
2618         } else
2619                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2620                         original->type, original->name);
2621         
2622         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2623            a zombie so nothing tries to touch it.  If it's already been marked as a
2624            zombie, then free it now (since it already is considered invalid). */
2625         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2626                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2627                 ast_mutex_unlock(&clone->lock);
2628                 ast_channel_free(clone);
2629                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2630         } else {
2631                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2632                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2633                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2634                 ast_queue_frame(clone, &null_frame);
2635                 ast_mutex_unlock(&clone->lock);
2636         }
2637         
2638         /* Signal any blocker */
2639         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2640                 pthread_kill(original->blocker, SIGURG);
2641         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2642                 original->name, original->_state);
2643         return 0;
2644 }
2645
2646 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2647 {
2648         if (callerid) {
2649                 if (chan->cid.cid_num)
2650                         free(chan->cid.cid_num);
2651                 if (ast_strlen_zero(callerid))
2652                         chan->cid.cid_num = NULL;
2653                 else
2654                         chan->cid.cid_num = strdup(callerid);
2655         }
2656         if (calleridname) {
2657                 if (chan->cid.cid_name)
2658                         free(chan->cid.cid_name);
2659                 if (ast_strlen_zero(calleridname))
2660                         chan->cid.cid_name = NULL;
2661                 else
2662                         chan->cid.cid_name = strdup(calleridname);
2663         }
2664         if (ani) {
2665                 if (chan->cid.cid_ani)
2666                         free(chan->cid.cid_ani);
2667                 if (ast_strlen_zero(ani))
2668                         chan->cid.cid_ani = NULL;
2669                 else
2670                         chan->cid.cid_ani = strdup(ani);
2671         }
2672         if (chan->cdr)
2673                 ast_cdr_setcid(chan->cdr, chan);
2674         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2675                                 "Channel: %s\r\n"
2676                                 "CallerID: %s\r\n"
2677                                 "CallerIDName: %s\r\n"
2678                                 "Uniqueid: %s\r\n",
2679                                 chan->name, chan->cid.cid_num ? 
2680                                 chan->cid.cid_num : "<Unknown>",
2681                                 chan->cid.cid_name ? 
2682                                 chan->cid.cid_name : "<Unknown>",
2683                                 chan->uniqueid);
2684 }
2685
2686 int ast_setstate(struct ast_channel *chan, int state)
2687 {
2688         if (chan->_state != state) {
2689                 int oldstate = chan->_state;
2690                 chan->_state = state;
2691                 if (oldstate == AST_STATE_DOWN) {
2692                         ast_device_state_changed(chan->name);
2693                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2694                         "Channel: %s\r\n"
2695                         "State: %s\r\n"
2696                         "CallerID: %s\r\n"
2697                         "CallerIDName: %s\r\n"
2698                         "Uniqueid: %s\r\n",
2699                         chan->name, ast_state2str(chan->_state), 
2700                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2701                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2702                         chan->uniqueid);
2703                 } else {
2704                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2705                                 "Channel: %s\r\n"
2706                                 "State: %s\r\n"
2707                                 "CallerID: %s\r\n"
2708                                 "CallerIDName: %s\r\n"
2709                                 "Uniqueid: %s\r\n",
2710                                 chan->name, ast_state2str(chan->_state), 
2711                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2712                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2713                                 chan->uniqueid);
2714                 }
2715         }
2716         return 0;
2717 }
2718
2719 static long tvdiff(struct timeval *now, struct timeval *then) 
2720 {
2721 #if 0
2722         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2723 #else
2724         return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;     
2725 #endif
2726 }
2727
2728 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2729 {
2730         struct ast_channel *bridged;
2731         bridged = chan->_bridge;
2732         if (bridged && bridged->tech->bridged_channel) 
2733                 bridged = bridged->tech->bridged_channel(chan, bridged);
2734         return bridged;
2735 }
2736
2737 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2738 {
2739         int res=0, min=0, sec=0,check=0;
2740
2741         check = ast_autoservice_start(peer);
2742         if(check) 
2743                 return;
2744
2745         if (remain > 0) {
2746                 if (remain / 60 > 1) {
2747                         min = remain / 60;
2748                         sec = remain % 60;
2749                 } else {
2750                         sec = remain;
2751                 }
2752         }
2753         
2754         if (!strcmp(sound,"timeleft")) {
2755                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2756                 res = ast_waitstream(chan, "");
2757                 if (min) {
2758                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2759                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2760                         res = ast_waitstream(chan, "");
2761                 }
2762                 if (sec) {
2763                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2764                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2765                         res = ast_waitstream(chan, "");
2766                 }
2767         } else {
2768                 res = ast_streamfile(chan, sound, chan->language);
2769                 res = ast_waitstream(chan, "");
2770         }
2771
2772         check = ast_autoservice_stop(peer);
2773 }
2774
2775 static int ast_generic_bridge(int *playitagain, int *playit, struct timeval *start_time, struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
2776 {
2777         /* Copy voice back and forth between the two channels.  Give the peer
2778            the ability to transfer calls with '#<extension' syntax. */
2779         struct ast_channel *cs[3];
2780         int to = -1;
2781         struct ast_frame *f;
2782         struct ast_channel *who = NULL;
2783         void *pvt0, *pvt1;
2784         int res=0;
2785         int o0nativeformats;
2786         int o1nativeformats;
2787         struct timeval precise_now;
2788         long elapsed_ms=0, time_left_ms=0;
2789         
2790         cs[0] = c0;
2791         cs[1] = c1;
2792         pvt0 = c0->pvt;
2793         pvt1 = c1->pvt;
2794         o0nativeformats = c0->nativeformats;
2795         o1nativeformats = c1->nativeformats;
2796
2797         for (;;) {
2798                 if ((c0->pvt != pvt0) || (c1->pvt != pvt1) ||
2799                     (o0nativeformats != c0->nativeformats) ||
2800                         (o1nativeformats != c1->nativeformats)) {
2801                         /* Check for Masquerade, codec changes, etc */
2802                         res = -3;
2803                         break;
2804                 }
2805                 /* timestamp */
2806                 if (config->timelimit) {
2807                         /* If there is a time limit, return now */
2808                         gettimeofday(&precise_now,NULL);
2809                         elapsed_ms = tvdiff(&precise_now,start_time);
2810                         time_left_ms = config->timelimit - elapsed_ms;
2811
2812                         if (*playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) { 
2813                                 res = -3;
2814                                 break;
2815                         }
2816                         if (time_left_ms <= 0) {
2817                                 res = -3;
2818                                 break;
2819                         }
2820                         if (time_left_ms >= 5000 && *playit) {
2821                                 res = -3;
2822                                 break;
2823                         }
2824                         
2825                 }
2826
2827                 who = ast_waitfor_n(cs, 2, &to);
2828                 if (!who) {
2829                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2830                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2831                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2832                 c0->_softhangup = 0;
2833             if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2834                 c1->_softhangup = 0;
2835                         c0->_bridge = c1;
2836                         c1->_bridge = c0;
2837                         continue;
2838                 }
2839
2840                         continue;
2841                 }
2842                 f = ast_read(who);
2843                 if (!f) {
2844                         *fo = NULL;
2845                         *rc = who;
2846                         res = 0;
2847                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2848                         break;
2849                 }
2850
2851                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2852                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2853                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2854                         } else {
2855                                 *fo = f;
2856                                 *rc = who;
2857                                 res =  0;
2858                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2859                                 break;
2860                         }
2861                 }
2862                 if ((f->frametype == AST_FRAME_VOICE) ||
2863                         (f->frametype == AST_FRAME_TEXT) ||
2864                         (f->frametype == AST_FRAME_VIDEO) || 
2865                         (f->frametype == AST_FRAME_IMAGE) ||
2866                         (f->frametype == AST_FRAME_HTML) ||
2867                         (f->frametype == AST_FRAME_DTMF)) {
2868
2869                         if ((f->frametype == AST_FRAME_DTMF) && 
2870                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2871                                 if ((who == c0)) {
2872                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2873                                                 *rc = c0;
2874                                                 *fo = f;
2875                                                 /* Take out of conference mode */
2876                                                 res = 0;
2877                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2878                                                 break;
2879                                         } else 
2880                                                 goto tackygoto;
2881                                 } else
2882                                 if ((who == c1)) {
2883                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2884                                                 *rc = c1;
2885                                                 *fo = f;
2886                                                 res =  0;
2887                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2888                                                 break;
2889                                         } else
2890                                                 goto tackygoto;
2891                                 }
2892                         } else {
2893 #if 0
2894                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2895                                 if (who == last) 
2896                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2897                                 last = who;
2898 #endif
2899 tackygoto:
2900                                 /* Don't copy packets if there is a generator on either one, since they're
2901                                    not supposed to be listening anyway */
2902                                 if (who == c0) 
2903                                         ast_write(c1, f);
2904                                 else 
2905                                         ast_write(c0, f);
2906                         }
2907                 }
2908                 ast_frfree(f);
2909
2910                 /* Swap who gets priority */
2911                 cs[2] = cs[0];
2912                 cs[0] = cs[1];
2913                 cs[1] = cs[2];
2914         }
2915         return res;
2916 }
2917
2918 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc) 
2919 {
2920         /* Copy voice back and forth between the two channels.  Give the peer
2921            the ability to transfer calls with '#<extension' syntax. */
2922         struct ast_channel *cs[3];
2923         struct ast_channel *who = NULL;
2924         int res=0;
2925         int nativefailed=0;
2926         int firstpass;
2927         int o0nativeformats;
2928         int o1nativeformats;
2929         struct timeval start_time,precise_now;
2930         long elapsed_ms=0, time_left_ms=0;
2931         int playit=0, playitagain=1, first_time=1;
2932
2933         *fo = NULL;
2934         firstpass = config->firstpass;
2935         config->firstpass = 0;
2936
2937         /* timestamp */
2938         gettimeofday(&start_time,NULL);
2939         time_left_ms = config->timelimit;
2940
2941         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2942                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2943         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2944                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2945
2946         /* Stop if we're a zombie or need a soft hangup */
2947         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) 
2948                 return -1;
2949         if (c0->_bridge) {
2950                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2951                         c0->name, c0->_bridge->name);
2952                 return -1;
2953         }
2954         if (c1->_bridge) {
2955                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2956                         c1->name, c1->_bridge->name);
2957                 return -1;
2958         }
2959         
2960         /* Keep track of bridge */
2961         c0->_bridge = c1;
2962         c1->_bridge = c0;
2963         cs[0] = c0;
2964         cs[1] = c1;
2965         
2966         manager_event(EVENT_FLAG_CALL, "Link", 
2967                         "Channel1: %s\r\n"
2968                         "Channel2: %s\r\n"
2969                         "Uniqueid1: %s\r\n"
2970                         "Uniqueid2: %s\r\n",
2971                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2972         o1nativeformats = c1->nativeformats;
2973         o0nativeformats = c0->nativeformats;
2974         for (/* ever */;;) {
2975                 /* timestamp */
2976                 if (config->timelimit) {
2977                         gettimeofday(&precise_now,NULL);
2978                         elapsed_ms = tvdiff(&precise_now,&start_time);
2979                         time_left_ms = config->timelimit - elapsed_ms;
2980
2981                         if (playitagain && ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) || (ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING))) && (config->play_warning && time_left_ms <= config->play_warning)) { 
2982                                 /* narrowing down to the end */
2983                                 if (config->warning_freq == 0) {
2984                                         playit = 1;
2985                                         first_time=0;
2986                                         playitagain=0;
2987                                 } else if (first_time) {
2988                                         playit = 1;
2989                                         first_time=0;
2990                                 } else {
2991                                         if ((time_left_ms % config->warning_freq) <= 50) {
2992                                                 playit = 1;
2993                                         }
2994                                 }
2995                         }
2996                         if (time_left_ms <= 0) {
2997                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2998                                         bridge_playfile(c0,c1,config->end_sound,0);
2999                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
3000                                         bridge_playfile(c1,c0,config->end_sound,0);
3001                                 *fo = NULL;
3002                                 if (who) *rc = who;
3003                                 res = 0;
3004                                 break;
3005                         }
3006                         if (time_left_ms >= 5000 && playit) {
3007                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3008                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
3009                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
3010                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
3011                                 playit = 0;
3012                         }
3013                         
3014                 }
3015
3016                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3017                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3018                                 c0->_softhangup = 0;
3019                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3020                                 c1->_softhangup = 0;
3021                         c0->_bridge = c1;
3022                         c1->_bridge = c0;
3023                         ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3024                         continue;
3025                 }
3026                 
3027                 /* Stop if we're a zombie or need a soft hangup */
3028                 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) || ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3029                         *fo = NULL;
3030                         if (who) *rc = who;
3031                         res = 0;
3032                         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,ast_test_flag(c0, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c0)?"Yes":"No",ast_test_flag(c1, AST_FLAG_ZOMBIE)?"Yes":"No",ast_check_hangup(c1)?"Yes":"No");
3033                         break;
3034                 }
3035                 if (c0->tech->bridge && config->timelimit==0 &&
3036                         (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3037                                 /* Looks like they share a bridge code */
3038                         if (option_verbose > 2) 
3039                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3040                         ast_set_flag(c0, AST_FLAG_NBRIDGE);
3041                         ast_set_flag(c1, AST_FLAG_NBRIDGE);
3042                         if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
3043                                 c0->_bridge = NULL;
3044                                 c1->_bridge = NULL;
3045                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
3046                                         "Channel1: %s\r\n"
3047                                         "Channel2: %s\r\n"
3048                                         "Uniqueid1: %s\r\n"
3049                                         "Uniqueid2: %s\r\n",
3050                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3051                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
3052                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3053                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3054                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3055                                         c0->_bridge = c1;
3056                                         c1->_bridge = c0;
3057                                         continue;
3058                                 }
3059                                 else 
3060                                 return 0;
3061                         } else {
3062                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3063                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3064                         }
3065                         
3066                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
3067                            my not wanting to bridge */
3068                         if ((res != -2) && (res != -3))
3069                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
3070                         if (res != -3) nativefailed++;
3071                 }
3072         
3073                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3074                         !(c0->generator || c1->generator))  {
3075                         if (ast_channel_make_compatible(c0, c1)) {
3076                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3077                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
3078                                         "Channel1: %s\r\n"
3079                                         "Channel2: %s\r\n"
3080                                         "Uniqueid1: %s\r\n"
3081                                         "Uniqueid2: %s\r\n",
3082                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3083                                 return -1;
3084                         }
3085                         o0nativeformats = c0->nativeformats;
3086                         o1nativeformats = c1->nativeformats;
3087                 }
3088                 res = ast_generic_bridge(&playitagain, &playit, &start_time, c0, c1, config, fo, rc);
3089                 if (res != -3)
3090                         break;
3091         }
3092         c0->_bridge = NULL;
3093         c1->_bridge = NULL;
3094         manager_event(EVENT_FLAG_CALL, "Unlink", 
3095                                         "Channel1: %s\r\n"
3096                                         "Channel2: %s\r\n"
3097                                         "Uniqueid1: %s\r\n"
3098                                         "Uniqueid2: %s\r\n",
3099                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3100         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
3101         return res;
3102 }
3103
3104 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3105 {
3106         int res;
3107         if (chan->tech->setoption) {
3108                 res = chan->tech->setoption(chan, option, data, datalen);
3109                 if (res < 0)
3110                         return res;
3111         } else {
3112                 errno = ENOSYS;
3113                 return -1;
3114         }
3115         if (block) {
3116                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
3117                    intermediate packets. XXX */
3118                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
3119                 return -1;
3120         }
3121         return 0;
3122 }
3123
3124 struct tonepair_def {
3125         int freq1;
3126         int freq2;
3127         int duration;
3128         int vol;
3129 };
3130
3131 struct tonepair_state {
3132         float freq1;
3133         float freq2;
3134         float vol;
3135         int duration;
3136         int pos;
3137         int origwfmt;
3138         struct ast_frame f;
3139         unsigned char offset[AST_FRIENDLY_OFFSET];
3140         short data[4000];
3141 };
3142
3143 static void tonepair_release(struct ast_channel *chan, void *params)
3144 {
3145         struct tonepair_state *ts = params;
3146         if (chan) {
3147                 ast_set_write_format(chan, ts->origwfmt);
3148         }
3149         free(ts);
3150 }
3151
3152 static void * tonepair_alloc(struct ast_channel *chan, void *params)
3153 {
3154         struct tonepair_state *ts;
3155         struct tonepair_def *td = params;
3156         ts = malloc(sizeof(struct tonepair_state));
3157         if (!ts)
3158                 return NULL;
3159         memset(ts, 0, sizeof(struct tonepair_state));
3160         ts->origwfmt = chan->writeformat;
3161         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
3162                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
3163                 tonepair_release(NULL, ts);
3164                 ts = NULL;
3165         } else {
3166                 ts->freq1 = td->freq1;
3167                 ts->freq2 = td->freq2;
3168                 ts->duration = td->duration;
3169                 ts->vol = td->vol;
3170         }
3171         /* Let interrupts interrupt :) */
3172         ast_set_flag(chan, AST_FLAG_WRITE_INT);
3173         return ts;
3174 }
3175
3176 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
3177 {
3178         struct tonepair_state *ts = data;
3179         int x;
3180
3181         /* we need to prepare a frame with 16 * timelen samples as we're 
3182          * generating SLIN audio
3183          */
3184         len = samples * 2;
3185
3186         if (len > sizeof(ts->data) / 2 - 1) {
3187                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
3188                 return -1;
3189         }
3190         memset(&ts->f, 0, sizeof(ts->f));
3191         for (x=0;x<len/2;x++) {
3192                 ts->data[x] = ts->vol * (
3193                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
3194                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
3195                         );
3196         }
3197         ts->f.frametype = AST_FRAME_VOICE;
3198         ts->f.subclass = AST_FORMAT_SLINEAR;
3199         ts->f.datalen = len;
3200         ts->f.samples = samples;
3201         ts->f.offset = AST_FRIENDLY_OFFSET;
3202         ts->f.data = ts->data;
3203         ast_write(chan, &ts->f);
3204         ts->pos += x;
3205         if (ts->duration > 0) {
3206                 if (ts->pos >= ts->duration * 8)
3207                         return -1;
3208         }
3209         return 0;
3210 }
3211
3212 static struct ast_generator tonepair = {
3213         alloc: tonepair_alloc,
3214         release: tonepair_release,
3215         generate: tonepair_generator,
3216 };
3217
3218 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3219 {
3220         struct tonepair_def d = { 0, };
3221         d.freq1 = freq1;
3222         d.freq2 = freq2;
3223         d.duration = duration;
3224         if (vol < 1)
3225                 d.vol = 8192;
3226         else
3227                 d.vol = vol;
3228         if (ast_activate_generator(chan, &tonepair, &d))
3229                 return -1;
3230         return 0;
3231 }
3232
3233 void ast_tonepair_stop(struct ast_channel *chan)
3234 {
3235         ast_deactivate_generator(chan);
3236 }
3237
3238 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3239 {
3240         struct ast_frame *f;
3241         int res;
3242         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3243                 return res;
3244
3245         /* Give us some wiggle room */
3246         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
3247                 f = ast_read(chan);
3248                 if (f)
3249                         ast_frfree(f);
3250                 else
3251                         return -1;
3252         }
3253         return 0;
3254 }
3255
3256 ast_group_t ast_get_group(char *s)
3257 {
3258         char *copy;
3259         char *piece;
3260         char *c=NULL;
3261         int start=0, finish=0,x;
3262         ast_group_t group = 0;
3263         copy = ast_strdupa(s);
3264         if (!copy) {
3265                 ast_log(LOG_ERROR, "Out of memory\n");
3266                 return 0;
3267         }
3268         c = copy;
3269         
3270         while((piece = strsep(&c, ","))) {
3271                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3272                         /* Range */
3273                 } else if (sscanf(piece, "%d", &start)) {
3274                         /* Just one */
3275                         finish = start;
3276                 } else {
3277                         ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'.\n", s, piece);
3278                         continue;
3279                 }
3280                 for (x=start;x<=finish;x++) {
3281                         if ((x > 63) || (x < 0)) {
3282                                 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
3283                         } else
3284                                 group |= (1 << x);
3285                 }
3286         }
3287         return group;
3288 }
3289
3290 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
3291 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3292 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3293
3294
3295 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
3296                                                                  void (*stop_ptr)(struct ast_channel *),
3297                                                                  void (*cleanup_ptr)(struct ast_channel *)
3298                                                                  ) 
3299 {
3300         ast_moh_start_ptr = start_ptr;
3301         ast_moh_stop_ptr = stop_ptr;
3302         ast_moh_cleanup_ptr = cleanup_ptr;
3303 }
3304
3305 void ast_uninstall_music_functions(void) 
3306 {
3307         ast_moh_start_ptr = NULL;
3308         ast_moh_stop_ptr = NULL;
3309         ast_moh_cleanup_ptr = NULL;
3310 }
3311
3312 /*! Turn on/off music on hold on a given channel */
3313
3314 int ast_moh_start(struct ast_channel *chan, char *mclass) 
3315 {
3316         if(ast_moh_start_ptr)
3317                 return ast_moh_start_ptr(chan, mclass);
3318
3319         if (option_verbose > 2)
3320                 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3321         
3322         return 0;
3323 }
3324
3325 void ast_moh_stop(struct ast_channel *chan) 
3326 {
3327         if(ast_moh_stop_ptr)
3328                 ast_moh_stop_ptr(chan);
3329 }
3330
3331 void ast_moh_cleanup(struct ast_channel *chan) 
3332 {
3333         if(ast_moh_cleanup_ptr)
3334         ast_moh_cleanup_ptr(chan);
3335 }
3336
3337 void ast_channels_init(void)
3338 {
3339         ast_cli_register(&cli_show_channeltypes);
3340 }
3341
3342 /*--- ast_print_group: Print call group and pickup group ---*/
3343 char *ast_print_group(char *buf, int buflen, ast_group_t group) 
3344 {
3345         unsigned int i;
3346         int first=1;
3347         char num[3];
3348
3349         buf[0] = '\0';
3350         
3351         if (!group)     /* Return empty string if no group */
3352                 return(buf);
3353
3354         for (i=0; i<=63; i++) { /* Max group is 63 */
3355                 if (group & (1 << i)) {
3356                         if (!first) {
3357                                 strncat(buf, ", ", buflen);
3358                         } else {
3359                                 first=0;
3360                         }
3361                         snprintf(num, sizeof(num), "%u", i);
3362                         strncat(buf, num, buflen);
3363                 }
3364         }
3365         return(buf);
3366 }