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