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