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