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