0e93848bfe2dd74c5072ec90653a2733aa31fe37
[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 > 100) {
735                 struct ast_frame *freef, *headf;
736
737                 ast_log(LOG_ERROR, "Too Many frames queued at once, flushing cache.");
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 #ifdef ZAPTEL_OPTIMIZATIONS
1286         int (*func)(void *);
1287         void *data;
1288         int res;
1289 #endif
1290         static struct ast_frame null_frame = 
1291         {
1292                 AST_FRAME_NULL,
1293         };
1294         
1295         ast_mutex_lock(&chan->lock);
1296         if (chan->masq) {
1297                 if (ast_do_masquerade(chan)) {
1298                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1299                         f = NULL;
1300                 } else
1301                         f =  &null_frame;
1302                 ast_mutex_unlock(&chan->lock);
1303                 return f;
1304         }
1305
1306         /* Stop if we're a zombie or need a soft hangup */
1307         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1308                 if (chan->generator)
1309                         ast_deactivate_generator(chan);
1310                 ast_mutex_unlock(&chan->lock);
1311                 return NULL;
1312         }
1313
1314         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1315                 /* We have DTMF that has been deferred.  Return it now */
1316                 chan->dtmff.frametype = AST_FRAME_DTMF;
1317                 chan->dtmff.subclass = chan->dtmfq[0];
1318                 /* Drop first digit */
1319                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1320                 ast_mutex_unlock(&chan->lock);
1321                 return &chan->dtmff;
1322         }
1323         
1324         /* Read and ignore anything on the alertpipe, but read only
1325            one sizeof(blah) per frame that we send from it */
1326         if (chan->alertpipe[0] > -1) {
1327                 read(chan->alertpipe[0], &blah, sizeof(blah));
1328         }
1329 #ifdef ZAPTEL_OPTIMIZATIONS
1330         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1331                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1332                 blah = -1;
1333                 /* IF we can't get event, assume it's an expired as-per the old interface */
1334                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1335                 if (res) 
1336                         blah = ZT_EVENT_TIMER_EXPIRED;
1337
1338                 if (blah == ZT_EVENT_TIMER_PING) {
1339 #if 0
1340                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1341 #endif                  
1342                         if (!chan->readq || !chan->readq->next) {
1343                                 /* Acknowledge PONG unless we need it again */
1344 #if 0
1345                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1346 #endif                          
1347                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1348                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1349                                 }
1350                         }
1351                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1352                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1353                         func = chan->timingfunc;
1354                         data = chan->timingdata;
1355                         ast_mutex_unlock(&chan->lock);
1356                         if (func) {
1357 #if 0
1358                                 ast_log(LOG_DEBUG, "Calling private function\n");
1359 #endif                  
1360                                 func(data);
1361                         } else {
1362                                 blah = 0;
1363                                 ast_mutex_lock(&chan->lock);
1364                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1365                                 chan->timingdata = NULL;
1366                                 ast_mutex_unlock(&chan->lock);
1367                         }
1368                         f =  &null_frame;
1369                         return f;
1370                 } else
1371                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1372         }
1373 #endif
1374         /* Check for pending read queue */
1375         if (chan->readq) {
1376                 f = chan->readq;
1377                 chan->readq = f->next;
1378                 /* Interpret hangup and return NULL */
1379                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1380                         ast_frfree(f);
1381                         f = NULL;
1382                 }
1383         } else {
1384                 chan->blocker = pthread_self();
1385                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1386                         if (chan->tech->exception) 
1387                                 f = chan->tech->exception(chan);
1388                         else {
1389                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1390                                 f = &null_frame;
1391                         }
1392                         /* Clear the exception flag */
1393                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1394                 } else
1395                 if (chan->tech->read)
1396                         f = chan->tech->read(chan);
1397                 else
1398                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1399         }
1400
1401
1402         if (f && (f->frametype == AST_FRAME_VOICE)) {
1403                 if (!(f->subclass & chan->nativeformats)) {
1404                         /* This frame can't be from the current native formats -- drop it on the
1405                            floor */
1406                         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));
1407                         ast_frfree(f);
1408                         f = &null_frame;
1409                 } else {
1410                         if (chan->spiers) {
1411                                 struct ast_channel_spy *spying;
1412                                 for (spying = chan->spiers; spying; spying=spying->next) {
1413                                         ast_queue_spy_frame(spying, f, 0);
1414                                 }
1415                         }
1416                         if (chan->monitor && chan->monitor->read_stream ) {
1417 #ifndef MONITOR_CONSTANT_DELAY
1418                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1419                                 if (jump >= 0) {
1420                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1421                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1422                                         chan->insmpl += jump + 2 * f->samples;
1423                                 } else
1424                                         chan->insmpl+= f->samples;
1425 #else
1426                                 int jump = chan->outsmpl - chan->insmpl;
1427                                 if (jump - MONITOR_DELAY >= 0) {
1428                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1429                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1430                                         chan->insmpl += jump;
1431                                 } else
1432                                         chan->insmpl += f->samples;
1433 #endif
1434                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1435                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1436                         }
1437                         if (chan->readtrans) {
1438                                 f = ast_translate(chan->readtrans, f, 1);
1439                                 if (!f)
1440                                         f = &null_frame;
1441                         }
1442                 }
1443         }
1444
1445         /* Make sure we always return NULL in the future */
1446         if (!f) {
1447                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1448                 if (chan->generator)
1449                         ast_deactivate_generator(chan);
1450                 /* End the CDR if appropriate */
1451                 if (chan->cdr)
1452                         ast_cdr_end(chan->cdr);
1453         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1454                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1455                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1456                 else
1457                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1458                 f = &null_frame;
1459         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1460                 if (chan->_state == AST_STATE_UP) {
1461                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1462                         f = &null_frame;
1463                 }
1464                 /* Answer the CDR */
1465                 ast_setstate(chan, AST_STATE_UP);
1466                 ast_cdr_answer(chan->cdr);
1467         } 
1468
1469         /* Run any generator sitting on the line */
1470         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1471                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1472                    will be calling the generator instead */
1473                 void *tmp;
1474                 int res;
1475                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1476                 if (chan->timingfunc) {
1477                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1478                         ast_settimeout(chan, 0, NULL, NULL);
1479                 }
1480                 tmp = chan->generatordata;
1481                 chan->generatordata = NULL;
1482                 generate = chan->generator->generate;
1483                 res = generate(chan, tmp, f->datalen, f->samples);
1484                 chan->generatordata = tmp;
1485                 if (res) {
1486                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1487                         ast_deactivate_generator(chan);
1488                 }
1489         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1490                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1491                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1492                         ast_settimeout(chan, 160, generator_force, chan);
1493                 }
1494         }
1495         if (chan->fin & 0x80000000)
1496                 ast_frame_dump(chan->name, f, "<<");
1497         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1498                 chan->fin &= 0x80000000;
1499         else
1500                 chan->fin++;
1501         ast_mutex_unlock(&chan->lock);
1502         return f;
1503 }
1504
1505 int ast_indicate(struct ast_channel *chan, int condition)
1506 {
1507         int res = -1;
1508         /* Stop if we're a zombie or need a soft hangup */
1509         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1510                 return -1;
1511         ast_mutex_lock(&chan->lock);
1512         if (chan->tech->indicate)
1513                 res = chan->tech->indicate(chan, condition);
1514         ast_mutex_unlock(&chan->lock);
1515         if (!chan->tech->indicate || res) {
1516                 /*
1517                  * Device does not support (that) indication, lets fake
1518                  * it by doing our own tone generation. (PM2002)
1519                  */
1520                 if (condition >= 0) {
1521                         const struct tone_zone_sound *ts = NULL;
1522                         switch (condition) {
1523                          case AST_CONTROL_RINGING:
1524                                 ts = ast_get_indication_tone(chan->zone, "ring");
1525                                 break;
1526                          case AST_CONTROL_BUSY:
1527                                 ts = ast_get_indication_tone(chan->zone, "busy");
1528                                 break;
1529                          case AST_CONTROL_CONGESTION:
1530                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1531                                 break;
1532                         }
1533                         if (ts && ts->data[0]) {
1534                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1535                                 ast_playtones_start(chan,0,ts->data, 1);
1536                                 res = 0;
1537                         } else if (condition == AST_CONTROL_PROGRESS) {
1538                                 /* ast_playtones_stop(chan); */
1539                         } else if (condition == AST_CONTROL_PROCEEDING) {
1540                                 /* Do nothing, really */
1541                         } else if (condition == AST_CONTROL_HOLD) {
1542                                 /* Do nothing.... */
1543                         } else if (condition == AST_CONTROL_UNHOLD) {
1544                                 /* Do nothing.... */
1545                         } else {
1546                                 /* not handled */
1547                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1548                                 res = -1;
1549                         }
1550                 }
1551                 else ast_playtones_stop(chan);
1552         }
1553         return res;
1554 }
1555
1556 int ast_recvchar(struct ast_channel *chan, int timeout)
1557 {
1558         int res,ourto,c;
1559         struct ast_frame *f;
1560         
1561         ourto = timeout;
1562         for(;;)
1563            {
1564                 if (ast_check_hangup(chan)) return -1;
1565                 res = ast_waitfor(chan,ourto);
1566                 if (res <= 0) /* if timeout */
1567                    {
1568                         return 0;
1569                    }
1570                 ourto = res;
1571                 f = ast_read(chan);
1572                 if (f == NULL) return -1; /* if hangup */
1573                 if ((f->frametype == AST_FRAME_CONTROL) &&
1574                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1575                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1576                    {
1577                         c = *((char *)f->data);  /* get the data */
1578                         ast_frfree(f);
1579                         return(c);
1580                    }
1581                 ast_frfree(f);
1582         }
1583 }
1584
1585 int ast_sendtext(struct ast_channel *chan, char *text)
1586 {
1587         int res = 0;
1588         /* Stop if we're a zombie or need a soft hangup */
1589         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1590                 return -1;
1591         CHECK_BLOCKING(chan);
1592         if (chan->tech->send_text)
1593                 res = chan->tech->send_text(chan, text);
1594         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1595         return res;
1596 }
1597
1598 static int do_senddigit(struct ast_channel *chan, char digit)
1599 {
1600         int res = -1;
1601
1602         if (chan->tech->send_digit)
1603                 res = chan->tech->send_digit(chan, digit);
1604         if (!chan->tech->send_digit || res) {
1605                 /*
1606                  * Device does not support DTMF tones, lets fake
1607                  * it by doing our own generation. (PM2002)
1608                  */
1609                 static const char* dtmf_tones[] = {
1610                         "!941+1336/100,!0/100", /* 0 */
1611                         "!697+1209/100,!0/100", /* 1 */
1612                         "!697+1336/100,!0/100", /* 2 */
1613                         "!697+1477/100,!0/100", /* 3 */
1614                         "!770+1209/100,!0/100", /* 4 */
1615                         "!770+1336/100,!0/100", /* 5 */
1616                         "!770+1477/100,!0/100", /* 6 */
1617                         "!852+1209/100,!0/100", /* 7 */
1618                         "!852+1336/100,!0/100", /* 8 */
1619                         "!852+1477/100,!0/100", /* 9 */
1620                         "!697+1633/100,!0/100", /* A */
1621                         "!770+1633/100,!0/100", /* B */
1622                         "!852+1633/100,!0/100", /* C */
1623                         "!941+1633/100,!0/100", /* D */
1624                         "!941+1209/100,!0/100", /* * */
1625                         "!941+1477/100,!0/100" };       /* # */
1626                 if (digit >= '0' && digit <='9')
1627                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1628                 else if (digit >= 'A' && digit <= 'D')
1629                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1630                 else if (digit == '*')
1631                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1632                 else if (digit == '#')
1633                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1634                 else {
1635                         /* not handled */
1636                         ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1637                 }
1638         }
1639         return 0;
1640 }
1641
1642 int ast_senddigit(struct ast_channel *chan, char digit)
1643 {
1644         return do_senddigit(chan, digit);
1645 }
1646
1647 int ast_prod(struct ast_channel *chan)
1648 {
1649         struct ast_frame a = { AST_FRAME_VOICE };
1650         char nothing[128];
1651         /* Send an empty audio frame to get things moving */
1652         if (chan->_state != AST_STATE_UP) {
1653                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1654                 a.subclass = chan->rawwriteformat;
1655                 a.data = nothing + AST_FRIENDLY_OFFSET;
1656                 a.src = "ast_prod";
1657                 if (ast_write(chan, &a))
1658                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1659         }
1660         return 0;
1661 }
1662
1663 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1664 {
1665         int res;
1666         if (!chan->tech->write_video)
1667                 return 0;
1668         res = ast_write(chan, fr);
1669         if (!res)
1670                 res = 1;
1671         return res;
1672 }
1673
1674 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1675 {
1676         int res = -1;
1677         struct ast_frame *f = NULL;
1678         /* Stop if we're a zombie or need a soft hangup */
1679         ast_mutex_lock(&chan->lock);
1680         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1681                 ast_mutex_unlock(&chan->lock);
1682                 return -1;
1683         }
1684         /* Handle any pending masquerades */
1685         if (chan->masq) {
1686                 if (ast_do_masquerade(chan)) {
1687                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1688                         ast_mutex_unlock(&chan->lock);
1689                         return -1;
1690                 }
1691         }
1692         if (chan->masqr) {
1693                 ast_mutex_unlock(&chan->lock);
1694                 return 0;
1695         }
1696         if (chan->generatordata) {
1697                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1698                         ast_deactivate_generator(chan);
1699                 else {
1700                         ast_mutex_unlock(&chan->lock);
1701                         return 0;
1702                 }
1703         }
1704         if (chan->fout & 0x80000000)
1705                 ast_frame_dump(chan->name, fr, ">>");
1706         CHECK_BLOCKING(chan);
1707         switch(fr->frametype) {
1708         case AST_FRAME_CONTROL:
1709                 /* XXX Interpret control frames XXX */
1710                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1711                 break;
1712         case AST_FRAME_DTMF:
1713                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1714                 ast_mutex_unlock(&chan->lock);
1715                 res = do_senddigit(chan,fr->subclass);
1716                 ast_mutex_lock(&chan->lock);
1717                 CHECK_BLOCKING(chan);
1718                 break;
1719         case AST_FRAME_TEXT:
1720                 if (chan->tech->send_text)
1721                         res = chan->tech->send_text(chan, (char *) fr->data);
1722                 else
1723                         res = 0;
1724                 break;
1725         case AST_FRAME_HTML:
1726                 if (chan->tech->send_html)
1727                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1728                 else
1729                         res = 0;
1730                 break;
1731         case AST_FRAME_VIDEO:
1732                 /* XXX Handle translation of video codecs one day XXX */
1733                 if (chan->tech->write_video)
1734                         res = chan->tech->write_video(chan, fr);
1735                 else
1736                         res = 0;
1737                 break;
1738         default:
1739                 if (chan->tech->write) {
1740                         if (chan->writetrans) {
1741                                 f = ast_translate(chan->writetrans, fr, 0);
1742                         } else
1743                                 f = fr;
1744                         if (f) {
1745                                 res = chan->tech->write(chan, f);
1746                                 if( chan->monitor &&
1747                                                 chan->monitor->write_stream &&
1748                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1749 #ifndef MONITOR_CONSTANT_DELAY
1750                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1751                                         if (jump >= 0) {
1752                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1753                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1754                                                 chan->outsmpl += jump + 2 * f->samples;
1755                                         } else
1756                                                 chan->outsmpl += f->samples;
1757 #else
1758                                         int jump = chan->insmpl - chan->outsmpl;
1759                                         if (jump - MONITOR_DELAY >= 0) {
1760                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1761                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1762                                                 chan->outsmpl += jump;
1763                                         } else
1764                                                 chan->outsmpl += f->samples;
1765 #endif
1766                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1767                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1768                                 }
1769                         } else
1770                                 res = 0;
1771                 }
1772         }
1773         if (f && (f != fr))
1774                 ast_frfree(f);
1775         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1776         /* Consider a write failure to force a soft hangup */
1777         if (res < 0)
1778                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1779         else {
1780                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1781                         chan->fout &= 0x80000000;
1782                 else
1783                         chan->fout++;
1784                 chan->fout++;
1785         }
1786         ast_mutex_unlock(&chan->lock);
1787         return res;
1788 }
1789
1790 int ast_set_write_format(struct ast_channel *chan, int fmts)
1791 {
1792         int fmt;
1793         int native;
1794         int res;
1795         
1796         ast_mutex_lock(&chan->lock);
1797         native = chan->nativeformats;
1798         fmt = fmts;
1799         
1800         res = ast_translator_best_choice(&native, &fmt);
1801         if (res < 0) {
1802                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1803                         ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1804                 ast_mutex_unlock(&chan->lock);
1805                 return -1;
1806         }
1807         
1808         /* Now we have a good choice for both.  We'll write using our native format. */
1809         chan->rawwriteformat = native;
1810         /* User perspective is fmt */
1811         chan->writeformat = fmt;
1812         /* Free any write translation we have right now */
1813         if (chan->writetrans)
1814                 ast_translator_free_path(chan->writetrans);
1815         /* Build a translation path from the user write format to the raw writing format */
1816         chan->writetrans = ast_translator_build_path(chan->rawwriteformat, chan->writeformat);
1817         if (option_debug)
1818                 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1819         ast_mutex_unlock(&chan->lock);
1820         return 0;
1821 }
1822
1823 int ast_set_read_format(struct ast_channel *chan, int fmts)
1824 {
1825         int fmt;
1826         int native;
1827         int res;
1828         
1829         ast_mutex_lock(&chan->lock);
1830         native = chan->nativeformats;
1831         fmt = fmts;
1832         /* Find a translation path from the native read format to one of the user's read formats */
1833         res = ast_translator_best_choice(&fmt, &native);
1834         if (res < 0) {
1835                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1836                         ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1837                 ast_mutex_unlock(&chan->lock);
1838                 return -1;
1839         }
1840         
1841         /* Now we have a good choice for both.  We'll write using our native format. */
1842         chan->rawreadformat = native;
1843         /* User perspective is fmt */
1844         chan->readformat = fmt;
1845         /* Free any read translation we have right now */
1846         if (chan->readtrans)
1847                 ast_translator_free_path(chan->readtrans);
1848         /* Build a translation path from the raw read format to the user reading format */
1849         chan->readtrans = ast_translator_build_path(chan->readformat, chan->rawreadformat);
1850         if (option_debug)
1851                 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n", 
1852                         chan->name, ast_getformatname(chan->readformat));
1853         ast_mutex_unlock(&chan->lock);
1854         return 0;
1855 }
1856
1857 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)
1858 {
1859         int state = 0;
1860         int cause = 0;
1861         struct ast_channel *chan;
1862         struct ast_frame *f;
1863         int res = 0;
1864         char *variable;
1865         chan = ast_request(type, format, data, &cause);
1866         if (chan) {
1867                 if (oh) {
1868                         char *tmp, *var;
1869                         /* JDG chanvar */
1870                         if (oh->variable)
1871                                 variable = ast_strdupa(oh->variable);
1872                         else
1873                                 variable = NULL;
1874                         tmp = variable;
1875                         /* FIXME replace this call with strsep  NOT*/
1876                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1877                                 pbx_builtin_setvar( chan, var );
1878                         } /* /JDG */
1879                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1880                         if (oh->account && *oh->account)
1881                                 ast_cdr_setaccount(chan, oh->account);
1882                 }
1883                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1884
1885                 if (!ast_call(chan, data, 0)) {
1886                         while(timeout && (chan->_state != AST_STATE_UP)) {
1887                                 res = ast_waitfor(chan, timeout);
1888                                 if (res < 0) {
1889                                         /* Something not cool, or timed out */
1890                                         break;
1891                                 }
1892                                 /* If done, break out */
1893                                 if (!res)
1894                                         break;
1895                                 if (timeout > -1)
1896                                         timeout = res;
1897                                 f = ast_read(chan);
1898                                 if (!f) {
1899                                         state = AST_CONTROL_HANGUP;
1900                                         res = 0;
1901                                         break;
1902                                 }
1903                                 if (f->frametype == AST_FRAME_CONTROL) {
1904                                         if (f->subclass == AST_CONTROL_RINGING)
1905                                                 state = AST_CONTROL_RINGING;
1906                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1907                                                 state = f->subclass;
1908                                                 ast_frfree(f);
1909                                                 break;
1910                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1911                                                 state = f->subclass;
1912                                                 ast_frfree(f);
1913                                                 break;
1914                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
1915                                                 /* Ignore */
1916                                         } else if (f->subclass == -1) {
1917                                                 /* Ignore -- just stopping indications */
1918                                         } else {
1919                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1920                                         }
1921                                 }
1922                                 ast_frfree(f);
1923                         }
1924                 } else
1925                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1926         } else {
1927                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1928                 switch(cause) {
1929                 case AST_CAUSE_BUSY:
1930                         state = AST_CONTROL_BUSY;
1931                         break;
1932                 case AST_CAUSE_CONGESTION:
1933                         state = AST_CONTROL_CONGESTION;
1934                         break;
1935                 }
1936         }
1937         if (chan) {
1938                 /* Final fixups */
1939                 if (oh) {
1940                         if (oh->context && *oh->context)
1941                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1942                         if (oh->exten && *oh->exten)
1943                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1944                         chan->priority = oh->priority;
1945                 }
1946                 if (chan->_state == AST_STATE_UP) 
1947                         state = AST_CONTROL_ANSWER;
1948         }
1949         if (outstate)
1950                 *outstate = state;
1951         if (chan && res <= 0) {
1952                 if (!chan->cdr) {
1953                         chan->cdr = ast_cdr_alloc();
1954                         if (chan->cdr)
1955                                 ast_cdr_init(chan->cdr, chan);
1956                 }
1957                 if (chan->cdr) {
1958                         char tmp[256];
1959                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
1960                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1961                         ast_cdr_update(chan);
1962                         ast_cdr_start(chan->cdr);
1963                         ast_cdr_end(chan->cdr);
1964                         /* If the cause wasn't handled properly */
1965                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1966                                 ast_cdr_failed(chan->cdr);
1967                 } else 
1968                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1969                 ast_hangup(chan);
1970                 chan = NULL;
1971         }
1972         return chan;
1973 }
1974
1975 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1976 {
1977         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1978 }
1979
1980 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1981 {
1982         struct chanlist *chan;
1983         struct ast_channel *c = NULL;
1984         int capabilities;
1985         int fmt;
1986         int res;
1987         int foo;
1988         if (!cause)
1989                 cause = &foo;
1990         *cause = AST_CAUSE_NOTDEFINED;
1991         if (ast_mutex_lock(&chlock)) {
1992                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1993                 return NULL;
1994         }
1995         chan = backends;
1996         while(chan) {
1997                 if (!strcasecmp(type, chan->tech->type)) {
1998                         capabilities = chan->tech->capabilities;
1999                         fmt = format;
2000                         res = ast_translator_best_choice(&fmt, &capabilities);
2001                         if (res < 0) {
2002                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2003                                 ast_mutex_unlock(&chlock);
2004                                 return NULL;
2005                         }
2006                         ast_mutex_unlock(&chlock);
2007                         if (chan->tech->requester)
2008                                 c = chan->tech->requester(type, capabilities, data, cause);
2009                         if (c) {
2010                                 if (c->_state == AST_STATE_DOWN) {
2011                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2012                                         "Channel: %s\r\n"
2013                                         "State: %s\r\n"
2014                                         "CallerID: %s\r\n"
2015                                         "CallerIDName: %s\r\n"
2016                                         "Uniqueid: %s\r\n",
2017                                         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);
2018                                 }
2019                         }
2020                         return c;
2021                 }
2022                 chan = chan->next;
2023         }
2024         if (!chan) {
2025                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2026                 *cause = AST_CAUSE_NOSUCHDRIVER;
2027         }
2028         ast_mutex_unlock(&chlock);
2029         return c;
2030 }
2031
2032 int ast_parse_device_state(char *device)
2033 {
2034         char name[AST_CHANNEL_NAME] = "";
2035         char *cut;
2036         struct ast_channel *chan;
2037
2038         chan = ast_channel_walk_locked(NULL);
2039         while (chan) {
2040                 strncpy(name, chan->name, sizeof(name)-1);
2041                 ast_mutex_unlock(&chan->lock);
2042                 cut = strchr(name,'-');
2043                 if (cut)
2044                         *cut = 0;
2045                 if (!strcmp(name, device))
2046                         return AST_DEVICE_INUSE;
2047                 chan = ast_channel_walk_locked(chan);
2048         }
2049         return AST_DEVICE_UNKNOWN;
2050 }
2051
2052 int ast_device_state(char *device)
2053 {
2054         char tech[AST_MAX_EXTENSION] = "";
2055         char *number;
2056         struct chanlist *chanls;
2057         int res = 0;
2058         
2059         strncpy(tech, device, sizeof(tech)-1);
2060         number = strchr(tech, '/');
2061         if (!number) {
2062             return AST_DEVICE_INVALID;
2063         }
2064         *number = 0;
2065         number++;
2066                 
2067         if (ast_mutex_lock(&chlock)) {
2068                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2069                 return -1;
2070         }
2071         chanls = backends;
2072         while(chanls) {
2073                 if (!strcasecmp(tech, chanls->tech->type)) {
2074                         ast_mutex_unlock(&chlock);
2075                         if (!chanls->tech->devicestate) 
2076                                 return ast_parse_device_state(device);
2077                         else {
2078                                 res = chanls->tech->devicestate(number);
2079                                 if (res == AST_DEVICE_UNKNOWN)
2080                                         return ast_parse_device_state(device);
2081                                 else
2082                                         return res;
2083                         }
2084                 }
2085                 chanls = chanls->next;
2086         }
2087         ast_mutex_unlock(&chlock);
2088         return AST_DEVICE_INVALID;
2089 }
2090
2091 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2092 {
2093         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2094            If the remote end does not answer within the timeout, then do NOT hang up, but 
2095            return anyway.  */
2096         int res = -1;
2097         /* Stop if we're a zombie or need a soft hangup */
2098         ast_mutex_lock(&chan->lock);
2099         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2100                 if (chan->tech->call)
2101                         res = chan->tech->call(chan, addr, timeout);
2102         ast_mutex_unlock(&chan->lock);
2103         return res;
2104 }
2105
2106 int ast_transfer(struct ast_channel *chan, char *dest) 
2107 {
2108         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2109            If the remote end does not answer within the timeout, then do NOT hang up, but 
2110            return anyway.  */
2111         int res = -1;
2112         /* Stop if we're a zombie or need a soft hangup */
2113         ast_mutex_lock(&chan->lock);
2114         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2115                 if (chan->tech->transfer) {
2116                         res = chan->tech->transfer(chan, dest);
2117                         if (!res)
2118                                 res = 1;
2119                 } else
2120                         res = 0;
2121         }
2122         ast_mutex_unlock(&chan->lock);
2123         return res;
2124 }
2125
2126 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2127 {
2128         int pos=0;
2129         int to = ftimeout;
2130         char d;
2131         /* XXX Merge with full version? XXX */
2132         /* Stop if we're a zombie or need a soft hangup */
2133         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2134                 return -1;
2135         if (!len)
2136                 return -1;
2137         do {
2138                 if (c->stream) {
2139                         d = ast_waitstream(c, AST_DIGIT_ANY);
2140                         ast_stopstream(c);
2141                         usleep(1000);
2142                         if (!d)
2143                                 d = ast_waitfordigit(c, to);
2144                 } else {
2145                         d = ast_waitfordigit(c, to);
2146                 }
2147                 if (d < 0)
2148                         return -1;
2149                 if (d == 0) {
2150                         s[pos]='\0';
2151                         return 1;
2152                 }
2153                 if (!strchr(enders, d))
2154                         s[pos++] = d;
2155                 if (strchr(enders, d) || (pos >= len)) {
2156                         s[pos]='\0';
2157                         return 0;
2158                 }
2159                 to = timeout;
2160         } while(1);
2161         /* Never reached */
2162         return 0;
2163 }
2164
2165 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2166 {
2167         int pos=0;
2168         int to = ftimeout;
2169         char d;
2170         /* Stop if we're a zombie or need a soft hangup */
2171         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2172                 return -1;
2173         if (!len)
2174                 return -1;
2175         do {
2176                 if (c->stream) {
2177                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2178                         ast_stopstream(c);
2179                         usleep(1000);
2180                         if (!d)
2181                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2182                 } else {
2183                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2184                 }
2185                 if (d < 0)
2186                         return -1;
2187                 if (d == 0) {
2188                         s[pos]='\0';
2189                         return 1;
2190                 }
2191                 if (d == 1) {
2192                         s[pos]='\0';
2193                         return 2;
2194                 }
2195                 if (!strchr(enders, d))
2196                         s[pos++] = d;
2197                 if (strchr(enders, d) || (pos >= len)) {
2198                         s[pos]='\0';
2199                         return 0;
2200                 }
2201                 to = timeout;
2202         } while(1);
2203         /* Never reached */
2204         return 0;
2205 }
2206
2207 int ast_channel_supports_html(struct ast_channel *chan)
2208 {
2209         if (chan->tech->send_html)
2210                 return 1;
2211         return 0;
2212 }
2213
2214 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
2215 {
2216         if (chan->tech->send_html)
2217                 return chan->tech->send_html(chan, subclass, data, datalen);
2218         return -1;
2219 }
2220
2221 int ast_channel_sendurl(struct ast_channel *chan, char *url)
2222 {
2223         if (chan->tech->send_html)
2224                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2225         return -1;
2226 }
2227
2228 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2229 {
2230         int peerf;
2231         int chanf;
2232         int res;
2233         ast_mutex_lock(&peer->lock);
2234         peerf = peer->nativeformats;
2235         ast_mutex_unlock(&peer->lock);
2236         ast_mutex_lock(&chan->lock);
2237         chanf = chan->nativeformats;
2238         ast_mutex_unlock(&chan->lock);
2239         res = ast_translator_best_choice(&peerf, &chanf);
2240         if (res < 0) {
2241                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2242                 return -1;
2243         }
2244         /* Set read format on channel */
2245         res = ast_set_read_format(chan, peerf);
2246         if (res < 0) {
2247                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2248                 return -1;
2249         }
2250         /* Set write format on peer channel */
2251         res = ast_set_write_format(peer, peerf);
2252         if (res < 0) {
2253                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2254                 return -1;
2255         }
2256         /* Now we go the other way */
2257         peerf = peer->nativeformats;
2258         chanf = chan->nativeformats;
2259         res = ast_translator_best_choice(&chanf, &peerf);
2260         if (res < 0) {
2261                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2262                 return -1;
2263         }
2264         /* Set writeformat on channel */
2265         res = ast_set_write_format(chan, chanf);
2266         if (res < 0) {
2267                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2268                 return -1;
2269         }
2270         /* Set read format on peer channel */
2271         res = ast_set_read_format(peer, chanf);
2272         if (res < 0) {
2273                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2274                 return -1;
2275         }
2276         return 0;
2277 }
2278
2279 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2280 {
2281         struct ast_frame null = { AST_FRAME_NULL, };
2282         int res = -1;
2283         if (original == clone) {
2284                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2285                 return -1;
2286         }
2287         ast_mutex_lock(&original->lock);
2288         while(ast_mutex_trylock(&clone->lock)) {
2289                 ast_mutex_unlock(&original->lock);
2290                 usleep(1);
2291                 ast_mutex_lock(&original->lock);
2292         }
2293         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2294                 clone->name, original->name);
2295         if (original->masq) {
2296                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2297                         original->masq->name, original->name);
2298         } else if (clone->masqr) {
2299                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2300                         clone->name, clone->masqr->name);
2301         } else {
2302                 original->masq = clone;
2303                 clone->masqr = original;
2304                 ast_queue_frame(original, &null);
2305                 ast_queue_frame(clone, &null);
2306                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2307                 res = 0;
2308         }
2309         ast_mutex_unlock(&clone->lock);
2310         ast_mutex_unlock(&original->lock);
2311         return res;
2312 }
2313
2314 void ast_change_name(struct ast_channel *chan, char *newname)
2315 {
2316         char tmp[256];
2317         strncpy(tmp, chan->name, sizeof(tmp) - 1);
2318         strncpy(chan->name, newname, sizeof(chan->name) - 1);
2319         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2320 }
2321
2322 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2323 {
2324         struct ast_var_t *current, *newvar;
2325         char *varname;
2326
2327         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2328                 int vartype = 0;
2329
2330                 varname = ast_var_full_name(current);
2331                 if (!varname)
2332                         continue;
2333
2334                 if (varname[0] == '_') {
2335                         vartype = 1;
2336                         if (varname[1] == '_')
2337                                 vartype = 2;
2338                 }
2339
2340                 switch (vartype) {
2341                 case 1:
2342                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2343                         if (newvar) {
2344                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2345                                 if (option_debug)
2346                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2347                         }
2348                         break;
2349                 case 2:
2350                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2351                         if (newvar) {
2352                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2353                                 if (option_debug)
2354                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2355                         }
2356                         break;
2357                 default:
2358                         if (option_debug)
2359                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2360                         break;
2361                 }
2362         }
2363 }
2364
2365 /* Clone channel variables from 'clone' channel into 'original' channel
2366    All variables except those related to app_groupcount are cloned
2367    Variables are actually _removed_ from 'clone' channel, presumably
2368    because it will subsequently be destroyed.
2369    Assumes locks will be in place on both channels when called.
2370 */
2371    
2372 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2373 {
2374         struct ast_var_t *varptr;
2375
2376         /* we need to remove all app_groupcount related variables from the original
2377            channel before merging in the clone's variables; any groups assigned to the
2378            original channel should be released, only those assigned to the clone
2379            should remain
2380         */
2381
2382         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2383                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2384                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2385                         ast_var_delete(varptr);
2386                 }
2387         }
2388         AST_LIST_TRAVERSE_SAFE_END;
2389
2390         /* Append variables from clone channel into original channel */
2391         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2392         if (AST_LIST_FIRST(&clone->varshead))
2393                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2394 }
2395
2396 /* Assumes channel will be locked when called */
2397 int ast_do_masquerade(struct ast_channel *original)
2398 {
2399         int x,i;
2400         int res=0;
2401         int origstate;
2402         struct ast_frame *cur, *prev;
2403         const struct ast_channel_tech *t;
2404         void *t_pvt;
2405         struct ast_callerid tmpcid;
2406         struct ast_channel *clone = original->masq;
2407         int rformat = original->readformat;
2408         int wformat = original->writeformat;
2409         char newn[100];
2410         char orig[100];
2411         char masqn[100];
2412         char zombn[100];
2413
2414 #if 1
2415         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2416                 clone->name, clone->_state, original->name, original->_state);
2417 #endif
2418         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2419            the clone channel into the original channel.  Start by killing off the original
2420            channel's backend.   I'm not sure we're going to keep this function, because 
2421            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2422
2423         /* We need the clone's lock, too */
2424         ast_mutex_lock(&clone->lock);
2425
2426         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2427
2428         /* Having remembered the original read/write formats, we turn off any translation on either
2429            one */
2430         free_translation(clone);
2431         free_translation(original);
2432
2433
2434         /* Unlink the masquerade */
2435         original->masq = NULL;
2436         clone->masqr = NULL;
2437         
2438         /* Save the original name */
2439         strncpy(orig, original->name, sizeof(orig) - 1);
2440         /* Save the new name */
2441         strncpy(newn, clone->name, sizeof(newn) - 1);
2442         /* Create the masq name */
2443         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2444                 
2445         /* Copy the name from the clone channel */
2446         strncpy(original->name, newn, sizeof(original->name)-1);
2447
2448         /* Mangle the name of the clone channel */
2449         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2450         
2451         /* Notify any managers of the change, first the masq then the other */
2452         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2453         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2454
2455         /* Swap the technlogies */      
2456         t = original->tech;
2457         original->tech = clone->tech;
2458         clone->tech = t;
2459
2460         t_pvt = original->tech_pvt;
2461         original->tech_pvt = clone->tech_pvt;
2462         clone->tech_pvt = t_pvt;
2463
2464         /* Swap the readq's */
2465         cur = original->readq;
2466         original->readq = clone->readq;
2467         clone->readq = cur;
2468
2469         /* Swap the alertpipes */
2470         for (i = 0; i < 2; i++) {
2471                 x = original->alertpipe[i];
2472                 original->alertpipe[i] = clone->alertpipe[i];
2473                 clone->alertpipe[i] = x;
2474         }
2475
2476         /* Swap the raw formats */
2477         x = original->rawreadformat;
2478         original->rawreadformat = clone->rawreadformat;
2479         clone->rawreadformat = x;
2480         x = original->rawwriteformat;
2481         original->rawwriteformat = clone->rawwriteformat;
2482         clone->rawwriteformat = x;
2483
2484         /* Save any pending frames on both sides.  Start by counting
2485          * how many we're going to need... */
2486         prev = NULL;
2487         cur = clone->readq;
2488         x = 0;
2489         while(cur) {
2490                 x++;
2491                 prev = cur;
2492                 cur = cur->next;
2493         }
2494         /* If we had any, prepend them to the ones already in the queue, and 
2495          * load up the alertpipe */
2496         if (prev) {
2497                 prev->next = original->readq;
2498                 original->readq = clone->readq;
2499                 clone->readq = NULL;
2500                 if (original->alertpipe[1] > -1) {
2501                         for (i=0;i<x;i++)
2502                                 write(original->alertpipe[1], &x, sizeof(x));
2503                 }
2504         }
2505         clone->_softhangup = AST_SOFTHANGUP_DEV;
2506
2507
2508         /* And of course, so does our current state.  Note we need not
2509            call ast_setstate since the event manager doesn't really consider
2510            these separate.  We do this early so that the clone has the proper
2511            state of the original channel. */
2512         origstate = original->_state;
2513         original->_state = clone->_state;
2514         clone->_state = origstate;
2515
2516         if (clone->tech->fixup){
2517                 res = clone->tech->fixup(original, clone);
2518                 if (res) 
2519                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2520         }
2521
2522         /* Start by disconnecting the original's physical side */
2523         if (clone->tech->hangup)
2524                 res = clone->tech->hangup(clone);
2525         if (res) {
2526                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2527                 ast_mutex_unlock(&clone->lock);
2528                 return -1;
2529         }
2530         
2531         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2532         /* Mangle the name of the clone channel */
2533         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2534         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2535
2536         /* Update the type. */
2537         original->type = clone->type;
2538         
2539         /* Keep the same language.  */
2540         strncpy(original->language, clone->language, sizeof(original->language));
2541         /* Copy the FD's */
2542         for (x=0;x<AST_MAX_FDS;x++) {
2543                 original->fds[x] = clone->fds[x];
2544         }
2545         clone_variables(original, clone);
2546         clone->varshead.first = NULL;
2547         /* Presense of ADSI capable CPE follows clone */
2548         original->adsicpe = clone->adsicpe;
2549         /* Bridge remains the same */
2550         /* CDR fields remain the same */
2551         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2552         /* Application and data remain the same */
2553         /* Clone exception  becomes real one, as with fdno */
2554         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2555         original->fdno = clone->fdno;
2556         /* Schedule context remains the same */
2557         /* Stream stuff stays the same */
2558         /* Keep the original state.  The fixup code will need to work with it most likely */
2559
2560         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2561            out. */
2562         tmpcid = original->cid;
2563         original->cid = clone->cid;
2564         clone->cid = tmpcid;
2565         
2566         /* Restore original timing file descriptor */
2567         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2568         
2569         /* Our native formats are different now */
2570         original->nativeformats = clone->nativeformats;
2571         
2572         /* Context, extension, priority, app data, jump table,  remain the same */
2573         /* pvt switches.  pbx stays the same, as does next */
2574         
2575         /* Set the write format */
2576         ast_set_write_format(original, wformat);
2577
2578         /* Set the read format */
2579         ast_set_read_format(original, rformat);
2580
2581         /* Copy the music class */
2582         strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2583
2584         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2585
2586         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2587            can fix up everything as best as possible */
2588         if (original->tech->fixup) {
2589                 res = original->tech->fixup(clone, original);
2590                 if (res) {
2591                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2592                                 original->type, original->name);
2593                         ast_mutex_unlock(&clone->lock);
2594                         return -1;
2595                 }
2596         } else
2597                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2598                         original->type, original->name);
2599         
2600         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2601            a zombie so nothing tries to touch it.  If it's already been marked as a
2602            zombie, then free it now (since it already is considered invalid). */
2603         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2604                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2605                 ast_mutex_unlock(&clone->lock);
2606                 ast_channel_free(clone);
2607                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2608         } else {
2609                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2610                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2611                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2612                 ast_queue_frame(clone, &null_frame);
2613                 ast_mutex_unlock(&clone->lock);
2614         }
2615         
2616         /* Signal any blocker */
2617         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2618                 pthread_kill(original->blocker, SIGURG);
2619         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2620                 original->name, original->_state);
2621         return 0;
2622 }
2623
2624 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2625 {
2626         if (callerid) {
2627                 if (chan->cid.cid_num)
2628                         free(chan->cid.cid_num);
2629                 if (ast_strlen_zero(callerid))
2630                         chan->cid.cid_num = NULL;
2631                 else
2632                         chan->cid.cid_num = strdup(callerid);
2633         }
2634         if (calleridname) {
2635                 if (chan->cid.cid_name)
2636                         free(chan->cid.cid_name);
2637                 if (ast_strlen_zero(calleridname))
2638                         chan->cid.cid_name = NULL;
2639                 else
2640                         chan->cid.cid_name = strdup(calleridname);
2641         }
2642         if (ani) {
2643                 if (chan->cid.cid_ani)
2644                         free(chan->cid.cid_ani);
2645                 if (ast_strlen_zero(ani))
2646                         chan->cid.cid_ani = NULL;
2647                 else
2648                         chan->cid.cid_ani = strdup(ani);
2649         }
2650         if (chan->cdr)
2651                 ast_cdr_setcid(chan->cdr, chan);
2652         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2653                                 "Channel: %s\r\n"
2654                                 "CallerID: %s\r\n"
2655                                 "CallerIDName: %s\r\n"
2656                                 "Uniqueid: %s\r\n",
2657                                 chan->name, chan->cid.cid_num ? 
2658                                 chan->cid.cid_num : "<Unknown>",
2659                                 chan->cid.cid_name ? 
2660                                 chan->cid.cid_name : "<Unknown>",
2661                                 chan->uniqueid);
2662 }
2663
2664 int ast_setstate(struct ast_channel *chan, int state)
2665 {
2666         if (chan->_state != state) {
2667                 int oldstate = chan->_state;
2668                 chan->_state = state;
2669                 if (oldstate == AST_STATE_DOWN) {
2670                         ast_device_state_changed(chan->name);
2671                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2672                         "Channel: %s\r\n"
2673                         "State: %s\r\n"
2674                         "CallerID: %s\r\n"
2675                         "CallerIDName: %s\r\n"
2676                         "Uniqueid: %s\r\n",
2677                         chan->name, ast_state2str(chan->_state), 
2678                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2679                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2680                         chan->uniqueid);
2681                 } else {
2682                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2683                                 "Channel: %s\r\n"
2684                                 "State: %s\r\n"
2685                                 "CallerID: %s\r\n"
2686                                 "CallerIDName: %s\r\n"
2687                                 "Uniqueid: %s\r\n",
2688                                 chan->name, ast_state2str(chan->_state), 
2689                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2690                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2691                                 chan->uniqueid);
2692                 }
2693         }
2694         return 0;
2695 }
2696
2697 static long tvdiff(struct timeval *now, struct timeval *then) 
2698 {
2699 #if 0
2700         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2701 #else
2702         return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;     
2703 #endif
2704 }
2705
2706 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2707 {
2708         struct ast_channel *bridged;
2709         bridged = chan->_bridge;
2710         if (bridged && bridged->tech->bridged_channel) 
2711                 bridged = bridged->tech->bridged_channel(chan, bridged);
2712         return bridged;
2713 }
2714
2715 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2716 {
2717         int res=0, min=0, sec=0,check=0;
2718
2719         check = ast_autoservice_start(peer);
2720         if(check) 
2721                 return;
2722
2723         if (remain > 0) {
2724                 if (remain / 60 > 1) {
2725                         min = remain / 60;
2726                         sec = remain % 60;
2727                 } else {
2728                         sec = remain;
2729                 }
2730         }
2731         
2732         if (!strcmp(sound,"timeleft")) {
2733                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2734                 res = ast_waitstream(chan, "");
2735                 if (min) {
2736                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2737                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2738                         res = ast_waitstream(chan, "");
2739                 }
2740                 if (sec) {
2741                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2742                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2743                         res = ast_waitstream(chan, "");
2744                 }
2745         } else {
2746                 res = ast_streamfile(chan, sound, chan->language);
2747                 res = ast_waitstream(chan, "");
2748         }
2749
2750         check = ast_autoservice_stop(peer);
2751 }
2752
2753 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) 
2754 {
2755         /* Copy voice back and forth between the two channels.  Give the peer
2756            the ability to transfer calls with '#<extension' syntax. */
2757         struct ast_channel *cs[3];
2758         int to = -1;
2759         struct ast_frame *f;
2760         struct ast_channel *who = NULL;
2761         int res=0;
2762         int nativefailed=0;
2763         int firstpass;
2764         int o0nativeformats;
2765         int o1nativeformats;
2766         struct timeval start_time,precise_now;
2767         long elapsed_ms=0, time_left_ms=0;
2768         int playit=0, playitagain=1, first_time=1;
2769
2770         *fo = NULL;
2771         firstpass = config->firstpass;
2772         config->firstpass = 0;
2773
2774         /* timestamp */
2775         gettimeofday(&start_time,NULL);
2776         time_left_ms = config->timelimit;
2777
2778         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2779                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2780         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2781                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2782
2783         /* Stop if we're a zombie or need a soft hangup */
2784         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)) 
2785                 return -1;
2786         if (c0->_bridge) {
2787                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2788                         c0->name, c0->_bridge->name);
2789                 return -1;
2790         }
2791         if (c1->_bridge) {
2792                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2793                         c1->name, c1->_bridge->name);
2794                 return -1;
2795         }
2796         
2797         /* Keep track of bridge */
2798         c0->_bridge = c1;
2799         c1->_bridge = c0;
2800         cs[0] = c0;
2801         cs[1] = c1;
2802         
2803         manager_event(EVENT_FLAG_CALL, "Link", 
2804                         "Channel1: %s\r\n"
2805                         "Channel2: %s\r\n"
2806                         "Uniqueid1: %s\r\n"
2807                         "Uniqueid2: %s\r\n",
2808                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2809         o1nativeformats = c1->nativeformats;
2810         o0nativeformats = c0->nativeformats;
2811         for (/* ever */;;) {
2812                 /* timestamp */
2813                 if (config->timelimit) {
2814                         gettimeofday(&precise_now,NULL);
2815                         elapsed_ms = tvdiff(&precise_now,&start_time);
2816                         time_left_ms = config->timelimit - elapsed_ms;
2817
2818                         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)) { 
2819                                 /* narrowing down to the end */
2820                                 if (config->warning_freq == 0) {
2821                                         playit = 1;
2822                                         first_time=0;
2823                                         playitagain=0;
2824                                 } else if (first_time) {
2825                                         playit = 1;
2826                                         first_time=0;
2827                                 } else {
2828                                         if ((time_left_ms % config->warning_freq) <= 50) {
2829                                                 playit = 1;
2830                                         }
2831                                 }
2832                         }
2833                         if (time_left_ms <= 0) {
2834                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2835                                         bridge_playfile(c0,c1,config->end_sound,0);
2836                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2837                                         bridge_playfile(c1,c0,config->end_sound,0);
2838                                 *fo = NULL;
2839                                 if (who) *rc = who;
2840                                 res = 0;
2841                                 break;
2842                         }
2843                         if (time_left_ms >= 5000 && playit) {
2844                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2845                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2846                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2847                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2848                                 playit = 0;
2849                         }
2850                         
2851                 }
2852
2853                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2854                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2855                                 c0->_softhangup = 0;
2856                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2857                                 c1->_softhangup = 0;
2858                         c0->_bridge = c1;
2859                         c1->_bridge = c0;
2860                         ast_log(LOG_DEBUG, "UNBRIDGE SIGNAL RECEIVED! ENDING NATIVE BRIDGE IF IT EXISTS.\n");
2861                         continue;
2862                 }
2863                 
2864                 /* Stop if we're a zombie or need a soft hangup */
2865                 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)) {
2866                         *fo = NULL;
2867                         if (who) *rc = who;
2868                         res = 0;
2869                         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");
2870                         break;
2871                 }
2872                 if (c0->tech->bridge && config->timelimit==0 &&
2873                         (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
2874                                 /* Looks like they share a bridge code */
2875                         if (option_verbose > 2) 
2876                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2877                         ast_set_flag(c0, AST_FLAG_NBRIDGE);
2878                         ast_set_flag(c1, AST_FLAG_NBRIDGE);
2879                         if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
2880                                 c0->_bridge = NULL;
2881                                 c1->_bridge = NULL;
2882                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2883                                         "Channel1: %s\r\n"
2884                                         "Channel2: %s\r\n"
2885                                         "Uniqueid1: %s\r\n"
2886                                         "Uniqueid2: %s\r\n",
2887                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2888                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2889                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
2890                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
2891                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2892                                         c0->_bridge = c1;
2893                                         c1->_bridge = c0;
2894                                         continue;
2895                                 }
2896                                 else 
2897                                 return 0;
2898                         } else {
2899                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
2900                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
2901                         }
2902                         
2903                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2904                            my not wanting to bridge */
2905                         if ((res != -2) && (res != -3))
2906                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2907                         if (res != -3) nativefailed++;
2908                 }
2909         
2910                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2911                         !(c0->generator || c1->generator))  {
2912                         if (ast_channel_make_compatible(c0, c1)) {
2913                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2914                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2915                                         "Channel1: %s\r\n"
2916                                         "Channel2: %s\r\n"
2917                                         "Uniqueid1: %s\r\n"
2918                                         "Uniqueid2: %s\r\n",
2919                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2920                                 return -1;
2921                         }
2922                         o0nativeformats = c0->nativeformats;
2923
2924                         o1nativeformats = c1->nativeformats;
2925                 }
2926                 who = ast_waitfor_n(cs, 2, &to);
2927                 if (!who) {
2928                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2929                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2930                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2931                 c0->_softhangup = 0;
2932             if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2933                 c1->_softhangup = 0;
2934                         c0->_bridge = c1;
2935                         c1->_bridge = c0;
2936                         continue;
2937                 }
2938
2939                         continue;
2940                 }
2941                 f = ast_read(who);
2942                 if (!f) {
2943                         *fo = NULL;
2944                         *rc = who;
2945                         res = 0;
2946                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2947                         break;
2948                 }
2949
2950                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2951                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2952                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2953                         } else {
2954                                 *fo = f;
2955                                 *rc = who;
2956                                 res =  0;
2957                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2958                                 break;
2959                         }
2960                 }
2961                 if ((f->frametype == AST_FRAME_VOICE) ||
2962                         (f->frametype == AST_FRAME_TEXT) ||
2963                         (f->frametype == AST_FRAME_VIDEO) || 
2964                         (f->frametype == AST_FRAME_IMAGE) ||
2965                         (f->frametype == AST_FRAME_HTML) ||
2966                         (f->frametype == AST_FRAME_DTMF)) {
2967
2968                         if ((f->frametype == AST_FRAME_DTMF) && 
2969                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2970                                 if ((who == c0)) {
2971                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2972                                                 *rc = c0;
2973                                                 *fo = f;
2974                                                 /* Take out of conference mode */
2975                                                 res = 0;
2976                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2977                                                 break;
2978                                         } else 
2979                                                 goto tackygoto;
2980                                 } else
2981                                 if ((who == c1)) {
2982                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2983                                                 *rc = c1;
2984                                                 *fo = f;
2985                                                 res =  0;
2986                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2987                                                 break;
2988                                         } else
2989                                                 goto tackygoto;
2990                                 }
2991                         } else {
2992 #if 0
2993                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2994                                 if (who == last) 
2995                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2996                                 last = who;
2997 #endif
2998 tackygoto:
2999                                 /* Don't copy packets if there is a generator on either one, since they're
3000                                    not supposed to be listening anyway */
3001                                 if (who == c0) 
3002                                         ast_write(c1, f);
3003                                 else 
3004                                         ast_write(c0, f);
3005                         }
3006                 }
3007                 ast_frfree(f);
3008
3009                 /* Swap who gets priority */
3010                 cs[2] = cs[0];
3011                 cs[0] = cs[1];
3012                 cs[1] = cs[2];
3013         }
3014         c0->_bridge = NULL;
3015         c1->_bridge = NULL;
3016         manager_event(EVENT_FLAG_CALL, "Unlink", 
3017                                         "Channel1: %s\r\n"
3018                                         "Channel2: %s\r\n"
3019                                         "Uniqueid1: %s\r\n"
3020                                         "Uniqueid2: %s\r\n",
3021                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
3022         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
3023         return res;
3024 }
3025
3026 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3027 {
3028         int res;
3029         if (chan->tech->setoption) {
3030                 res = chan->tech->setoption(chan, option, data, datalen);
3031                 if (res < 0)
3032                         return res;
3033         } else {
3034                 errno = ENOSYS;
3035                 return -1;
3036         }
3037         if (block) {
3038                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
3039                    intermediate packets. XXX */
3040                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
3041                 return -1;
3042         }
3043         return 0;
3044 }
3045
3046 struct tonepair_def {
3047         int freq1;
3048         int freq2;
3049         int duration;
3050         int vol;
3051 };
3052
3053 struct tonepair_state {
3054         float freq1;
3055         float freq2;
3056         float vol;
3057         int duration;
3058         int pos;
3059         int origwfmt;
3060         struct ast_frame f;
3061         unsigned char offset[AST_FRIENDLY_OFFSET];
3062         short data[4000];
3063 };
3064
3065 static void tonepair_release(struct ast_channel *chan, void *params)
3066 {
3067         struct tonepair_state *ts = params;
3068         if (chan) {
3069                 ast_set_write_format(chan, ts->origwfmt);
3070         }
3071         free(ts);
3072 }
3073
3074 static void * tonepair_alloc(struct ast_channel *chan, void *params)
3075 {
3076         struct tonepair_state *ts;
3077         struct tonepair_def *td = params;
3078         ts = malloc(sizeof(struct tonepair_state));
3079         if (!ts)
3080                 return NULL;
3081         memset(ts, 0, sizeof(struct tonepair_state));
3082         ts->origwfmt = chan->writeformat;
3083         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
3084                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
3085                 tonepair_release(NULL, ts);
3086                 ts = NULL;
3087         } else {
3088                 ts->freq1 = td->freq1;
3089                 ts->freq2 = td->freq2;
3090                 ts->duration = td->duration;
3091                 ts->vol = td->vol;
3092         }
3093         /* Let interrupts interrupt :) */
3094         ast_set_flag(chan, AST_FLAG_WRITE_INT);
3095         return ts;
3096 }
3097
3098 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
3099 {
3100         struct tonepair_state *ts = data;
3101         int x;
3102
3103         /* we need to prepare a frame with 16 * timelen samples as we're 
3104          * generating SLIN audio
3105          */
3106         len = samples * 2;