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