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