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