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