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