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