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