Add sounds and update config files
[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         if (tmp) {
283                 memset(tmp, 0, sizeof(struct ast_channel));
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         if ((fd = chan->timingfd) > -1)
552                 close(fd);
553         f = chan->pvt->readq;
554         chan->pvt->readq = NULL;
555         while(f) {
556                 fp = f;
557                 f = f->next;
558                 ast_frfree(fp);
559         }
560         
561         /* loop over the variables list, freeing all data and deleting list items */
562         /* no need to lock the list, as the channel is already locked */
563         
564         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
565                     vardata = AST_LIST_FIRST(headp);
566                     AST_LIST_REMOVE_HEAD(headp, entries);
567 //                  printf("deleting var %s=%s\n",ast_var_name(vardata),ast_var_value(vardata));
568                     ast_var_delete(vardata);
569         }
570                                                          
571
572         free(chan->pvt);
573         chan->pvt = NULL;
574         free(chan);
575         PTHREAD_MUTEX_UNLOCK(&chlock);
576
577         ast_device_state_changed(name);
578 }
579
580 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
581 {
582         int res = 0;
583         struct ast_frame f = { AST_FRAME_NULL };
584         if (option_debug)
585                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
586         /* Inform channel driver that we need to be hung up, if it cares */
587         chan->_softhangup |= cause;
588         ast_queue_frame(chan, &f, 0);
589         /* Interrupt any select call or such */
590         if (chan->blocking)
591                 pthread_kill(chan->blocker, SIGURG);
592         return res;
593 }
594
595 int ast_softhangup(struct ast_channel *chan, int cause)
596 {
597         int res;
598         ast_pthread_mutex_lock(&chan->lock);
599         res = ast_softhangup_nolock(chan, cause);
600         ast_pthread_mutex_unlock(&chan->lock);
601         return res;
602 }
603
604 static int ast_do_masquerade(struct ast_channel *original);
605
606 static void free_translation(struct ast_channel *clone)
607 {
608         if (clone->pvt->writetrans)
609                 ast_translator_free_path(clone->pvt->writetrans);
610         if (clone->pvt->readtrans)
611                 ast_translator_free_path(clone->pvt->readtrans);
612         clone->pvt->writetrans = NULL;
613         clone->pvt->readtrans = NULL;
614         clone->pvt->rawwriteformat = clone->nativeformats;
615         clone->pvt->rawreadformat = clone->nativeformats;
616 }
617
618 int ast_hangup(struct ast_channel *chan)
619 {
620         int res = 0;
621         /* Don't actually hang up a channel that will masquerade as someone else, or
622            if someone is going to masquerade as us */
623         ast_pthread_mutex_lock(&chan->lock);
624         if (chan->masq) {
625                 if (ast_do_masquerade(chan)) 
626                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
627         }
628
629         if (chan->masq) {
630                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
631                 ast_pthread_mutex_unlock(&chan->lock);
632                 return 0;
633         }
634         /* If this channel is one which will be masqueraded into something, 
635            mark it as a zombie already, so we know to free it later */
636         if (chan->masqr) {
637                 ast_pthread_mutex_unlock(&chan->lock);
638                 chan->zombie=1;
639                 return 0;
640         }
641         free_translation(chan);
642         if (chan->stream)
643                 ast_stopstream(chan);
644         if (chan->sched)
645                 sched_context_destroy(chan->sched);
646         /* Clear any tone stuff remaining */
647         if (chan->generatordata)
648                 chan->generator->release(chan, chan->generatordata);
649         chan->generatordata = NULL;
650         chan->generator = NULL;
651         if (chan->cdr) {
652                 /* End the CDR if it hasn't already */
653                 ast_cdr_end(chan->cdr);
654                 /* Post and Free the CDR */
655                 ast_cdr_post(chan->cdr);
656                 ast_cdr_free(chan->cdr);
657         }
658         if (chan->blocking) {
659                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
660                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
661                                         pthread_self(), chan->name, chan->blocker, chan->blockproc);
662                 CRASH;
663         }
664         if (!chan->zombie) {
665                 if (option_debug)
666                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
667                 if (chan->pvt->hangup)
668                         res = chan->pvt->hangup(chan);
669         } else
670                 if (option_debug)
671                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
672                         
673         ast_pthread_mutex_unlock(&chan->lock);
674         manager_event(EVENT_FLAG_CALL, "Hangup", 
675                         "Channel: %s\r\n"
676                         "Uniqueid: %s\r\n",
677                         chan->name, chan->uniqueid);
678         ast_channel_free(chan);
679         return res;
680 }
681
682 void ast_channel_unregister(char *type)
683 {
684         struct chanlist *chan, *last=NULL;
685         if (option_debug)
686                 ast_log(LOG_DEBUG, "Unregistering channel type '%s'\n", type);
687         if (PTHREAD_MUTEX_LOCK(&chlock)) {
688                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
689                 return;
690         }
691         chan = backends;
692         while(chan) {
693                 if (!strcasecmp(chan->type, type)) {
694                         if (last)
695                                 last->next = chan->next;
696                         else
697                                 backends = backends->next;
698                         free(chan);
699                         PTHREAD_MUTEX_UNLOCK(&chlock);
700                         return;
701                 }
702                 last = chan;
703                 chan = chan->next;
704         }
705         PTHREAD_MUTEX_UNLOCK(&chlock);
706 }
707
708 int ast_answer(struct ast_channel *chan)
709 {
710         int res = 0;
711         /* Stop if we're a zombie or need a soft hangup */
712         if (chan->zombie || ast_check_hangup(chan)) 
713                 return -1;
714         switch(chan->_state) {
715         case AST_STATE_RINGING:
716         case AST_STATE_RING:
717                 if (chan->pvt->answer)
718                         res = chan->pvt->answer(chan);
719                 ast_setstate(chan, AST_STATE_UP);
720                 if (chan->cdr)
721                         ast_cdr_answer(chan->cdr);
722                 return res;
723                 break;
724         case AST_STATE_UP:
725                 if (chan->cdr)
726                         ast_cdr_answer(chan->cdr);
727                 break;
728         }
729         return 0;
730 }
731
732 void ast_deactivate_generator(struct ast_channel *chan)
733 {
734         if (chan->generatordata) {
735                 chan->generator->release(chan, chan->generatordata);
736                 chan->generatordata = NULL;
737                 chan->generator = NULL;
738                 chan->writeinterrupt = 0;
739         }
740 }
741
742 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
743 {
744         if (chan->generatordata) {
745                 chan->generator->release(chan, chan->generatordata);
746                 chan->generatordata = NULL;
747         }
748         ast_prod(chan);
749         if ((chan->generatordata = gen->alloc(chan, params))) {
750                 chan->generator = gen;
751         } else {
752                 return -1;
753         }
754         return 0;
755 }
756
757 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
758 {
759         /* Wait for x amount of time on a file descriptor to have input.  */
760         struct timeval tv;
761         fd_set rfds, efds;
762         int res;
763         int x, max=-1;
764         int winner = -1;
765         
766         tv.tv_sec = *ms / 1000;
767         tv.tv_usec = (*ms % 1000) * 1000;
768         FD_ZERO(&rfds);
769         FD_ZERO(&efds);
770         for (x=0;x<n;x++) {
771                 if (fds[x] > -1) {
772                         FD_SET(fds[x], &rfds);
773                         FD_SET(fds[x], &efds);
774                         if (fds[x] > max)
775                                 max = fds[x];
776                 }
777         }
778         if (*ms >= 0)
779                 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
780         else
781                 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
782
783         if (res < 0) {
784                 /* Simulate a timeout if we were interrupted */
785                 if (errno != EINTR)
786                         *ms = -1;
787                 else
788                         *ms = 0;
789                 return -1;
790         }
791
792         for (x=0;x<n;x++) {
793                 if ((fds[x] > -1) && (FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && (winner < 0)) {
794                         if (exception)
795                                 *exception = FD_ISSET(fds[x], &efds);
796                         winner = fds[x];
797                 }
798         }
799         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
800         return winner;
801 }
802
803 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
804         int *exception, int *outfd, int *ms)
805 {
806         /* Wait for x amount of time on a file descriptor to have input.  */
807         struct timeval tv;
808         fd_set rfds, efds;
809         int res;
810         int x, y, max=-1;
811         struct ast_channel *winner = NULL;
812         if (outfd)
813                 *outfd = -1;
814         if (exception)
815                 *exception = 0;
816         
817         /* Perform any pending masquerades */
818         for (x=0;x<n;x++) {
819                 ast_pthread_mutex_lock(&c[x]->lock);
820                 if (c[x]->masq) {
821                         if (ast_do_masquerade(c[x])) {
822                                 ast_log(LOG_WARNING, "Masquerade failed\n");
823                                 *ms = -1;
824                                 ast_pthread_mutex_unlock(&c[x]->lock);
825                                 return NULL;
826                         }
827                 }
828                 ast_pthread_mutex_unlock(&c[x]->lock);
829         }
830         
831         tv.tv_sec = *ms / 1000;
832         tv.tv_usec = (*ms % 1000) * 1000;
833         FD_ZERO(&rfds);
834         FD_ZERO(&efds);
835
836         for (x=0;x<n;x++) {
837                 for (y=0;y<AST_MAX_FDS;y++) {
838                         if (c[x]->fds[y] > -1) {
839                                 FD_SET(c[x]->fds[y], &rfds);
840                                 FD_SET(c[x]->fds[y], &efds);
841                                 if (c[x]->fds[y] > max)
842                                         max = c[x]->fds[y];
843                         }
844                 }
845                 CHECK_BLOCKING(c[x]);
846         }
847         for (x=0;x<nfds; x++) {
848                 FD_SET(fds[x], &rfds);
849                 FD_SET(fds[x], &efds);
850                 if (fds[x] > max)
851                         max = fds[x];
852         }
853         if (*ms >= 0)
854                 res = ast_select(max + 1, &rfds, NULL, &efds, &tv);
855         else
856                 res = ast_select(max + 1, &rfds, NULL, &efds, NULL);
857
858         if (res < 0) {
859                 for (x=0;x<n;x++) 
860                         c[x]->blocking = 0;
861                 /* Simulate a timeout if we were interrupted */
862                 if (errno != EINTR)
863                         *ms = -1;
864                 else {
865                         /* Just an interrupt */
866 #if 0
867                         *ms = 0;
868 #endif                  
869                 }
870                 return NULL;
871         }
872
873         for (x=0;x<n;x++) {
874                 c[x]->blocking = 0;
875                 for (y=0;y<AST_MAX_FDS;y++) {
876                         if (c[x]->fds[y] > -1) {
877                                 if ((FD_ISSET(c[x]->fds[y], &rfds) || FD_ISSET(c[x]->fds[y], &efds)) && !winner) {
878                                         /* Set exception flag if appropriate */
879                                         if (FD_ISSET(c[x]->fds[y], &efds))
880                                                 c[x]->exception = 1;
881                                         c[x]->fdno = y;
882                                         winner = c[x];
883                                 }
884                         }
885                 }
886         }
887         for (x=0;x<nfds;x++) {
888                 if ((FD_ISSET(fds[x], &rfds) || FD_ISSET(fds[x], &efds)) && !winner) {
889                         if (outfd)
890                                 *outfd = fds[x];
891                         if (FD_ISSET(fds[x], &efds) && exception)
892                                 *exception = 1;
893                         winner = NULL;
894                 }
895         }
896         *ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
897         return winner;
898 }
899
900 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
901 {
902         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
903 }
904
905 int ast_waitfor(struct ast_channel *c, int ms)
906 {
907         struct ast_channel *chan;
908         int oldms = ms;
909         chan = ast_waitfor_n(&c, 1, &ms);
910         if (ms < 0) {
911                 if (oldms < 0)
912                         return 0;
913                 else
914                         return -1;
915         }
916         return ms;
917 }
918
919 char ast_waitfordigit(struct ast_channel *c, int ms)
920 {
921         /* XXX Should I be merged with waitfordigit_full XXX */
922         struct ast_frame *f;
923         char result = 0;
924         /* Stop if we're a zombie or need a soft hangup */
925         if (c->zombie || ast_check_hangup(c)) 
926                 return -1;
927         /* Wait for a digit, no more than ms milliseconds total. */
928         while(ms && !result) {
929                 ms = ast_waitfor(c, ms);
930                 if (ms < 0) /* Error */
931                         result = -1; 
932                 else if (ms > 0) {
933                         /* Read something */
934                         f = ast_read(c);
935                         if (f) {
936                                 if (f->frametype == AST_FRAME_DTMF) 
937                                         result = f->subclass;
938                                 ast_frfree(f);
939                         } else
940                                 result = -1;
941                 }
942         }
943         return result;
944 }
945
946 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
947 {
948         int res = -1;
949 #ifdef ZAPTEL_OPTIMIZATIONS
950         if (c->timingfd > -1) {
951                 if (!func) {
952                         samples = 0;
953                         data = 0;
954                 }
955                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
956                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
957                 c->timingfunc = func;
958                 c->timingdata = data;
959         }
960 #endif  
961         return res;
962 }
963 char ast_waitfordigit_full(struct ast_channel *c, int ms, int audio, int ctrl)
964 {
965         struct ast_frame *f;
966         char result = 0;
967         struct ast_channel *rchan;
968         int outfd;
969         /* Stop if we're a zombie or need a soft hangup */
970         if (c->zombie || ast_check_hangup(c)) 
971                 return -1;
972         /* Wait for a digit, no more than ms milliseconds total. */
973         while(ms && !result) {
974                 rchan = ast_waitfor_nandfds(&c, 1, &audio, (audio > -1) ? 1 : 0, NULL, &outfd, &ms);
975                 if ((!rchan) && (outfd < 0) && (ms)) /* Error */
976                         result = -1; 
977                 else if (outfd > -1) {
978                         result = 1;
979                 } else if (rchan) {
980                         /* Read something */
981                         f = ast_read(c);
982                         if (f) {
983                                 if (f->frametype == AST_FRAME_DTMF) 
984                                         result = f->subclass;
985                                 ast_frfree(f);
986                         } else
987                                 result = -1;
988                 }
989         }
990         return result;
991 }
992
993 struct ast_frame *ast_read(struct ast_channel *chan)
994 {
995         struct ast_frame *f = NULL;
996         int blah;
997 #ifdef ZAPTEL_OPTIMIZATIONS
998         int (*func)(void *);
999         void *data;
1000 #endif
1001         static struct ast_frame null_frame = 
1002         {
1003                 AST_FRAME_NULL,
1004         };
1005         
1006         ast_pthread_mutex_lock(&chan->lock);
1007         if (chan->masq) {
1008                 if (ast_do_masquerade(chan)) {
1009                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1010                         f = NULL;
1011                 } else
1012                         f =  &null_frame;
1013                 pthread_mutex_unlock(&chan->lock);
1014                 return f;
1015         }
1016
1017         /* Stop if we're a zombie or need a soft hangup */
1018         if (chan->zombie || ast_check_hangup(chan)) {
1019                 if (chan->generator)
1020                         ast_deactivate_generator(chan);
1021                 pthread_mutex_unlock(&chan->lock);
1022                 return NULL;
1023         }
1024
1025         if (!chan->deferdtmf && strlen(chan->dtmfq)) {
1026                 /* We have DTMF that has been deferred.  Return it now */
1027                 chan->dtmff.frametype = AST_FRAME_DTMF;
1028                 chan->dtmff.subclass = chan->dtmfq[0];
1029                 /* Drop first digit */
1030                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1031                 pthread_mutex_unlock(&chan->lock);
1032                 return &chan->dtmff;
1033         }
1034         
1035         /* Read and ignore anything on the alertpipe, but read only
1036            one sizeof(blah) per frame that we send from it */
1037         if (chan->pvt->alertpipe[0] > -1) {
1038                 read(chan->pvt->alertpipe[0], &blah, sizeof(blah));
1039         }
1040 #ifdef ZAPTEL_OPTIMIZATIONS
1041         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && chan->exception) {
1042                 chan->exception = 0;
1043                 blah = -1;
1044                 ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1045                 func = chan->timingfunc;
1046                 data = chan->timingdata;
1047                 pthread_mutex_unlock(&chan->lock);
1048                 if (func) {
1049 #if 0
1050                         ast_log(LOG_DEBUG, "Calling private function\n");
1051 #endif                  
1052                         func(data);
1053                 } else {
1054                         blah = 0;
1055                         pthread_mutex_lock(&chan->lock);
1056                         ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1057                         chan->timingdata = NULL;
1058                         pthread_mutex_unlock(&chan->lock);
1059                 }
1060                 f =  &null_frame;
1061                 return f;
1062         }
1063 #endif
1064         /* Check for pending read queue */
1065         if (chan->pvt->readq) {
1066                 f = chan->pvt->readq;
1067                 chan->pvt->readq = f->next;
1068                 /* Interpret hangup and return NULL */
1069                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP))
1070                         f = NULL;
1071         } else {
1072                 chan->blocker = pthread_self();
1073                 if (chan->exception) {
1074                         if (chan->pvt->exception) 
1075                                 f = chan->pvt->exception(chan);
1076                         else {
1077                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1078                                 f = &null_frame;
1079                         }
1080                         /* Clear the exception flag */
1081                         chan->exception = 0;
1082                 } else
1083                 if (chan->pvt->read)
1084                         f = chan->pvt->read(chan);
1085                 else
1086                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1087         }
1088
1089
1090         if (f && (f->frametype == AST_FRAME_VOICE)) {
1091                 if (!(f->subclass & chan->nativeformats)) {
1092                         /* This frame can't be from the current native formats -- drop it on the
1093                            floor */
1094                         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);
1095                         ast_frfree(f);
1096                         f = &null_frame;
1097                 } else {
1098                         if (chan->monitor && chan->monitor->read_stream ) {
1099                                 if( ast_writestream( chan->monitor->read_stream, f ) < 0 ) {
1100                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1101                                 }
1102                         }
1103                         if (chan->pvt->readtrans) {
1104                                 f = ast_translate(chan->pvt->readtrans, f, 1);
1105                                 if (!f)
1106                                         f = &null_frame;
1107                         }
1108                 }
1109         }
1110
1111         /* Make sure we always return NULL in the future */
1112         if (!f) {
1113                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1114                 if (chan->generator)
1115                         ast_deactivate_generator(chan);
1116                 /* End the CDR if appropriate */
1117                 if (chan->cdr)
1118                         ast_cdr_end(chan->cdr);
1119         } else if (chan->deferdtmf && f->frametype == AST_FRAME_DTMF) {
1120                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1121                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1122                 else
1123                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1124                 f = &null_frame;
1125         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1126                 /* Answer the CDR */
1127                 ast_setstate(chan, AST_STATE_UP);
1128                 ast_cdr_answer(chan->cdr);
1129         } 
1130         pthread_mutex_unlock(&chan->lock);
1131
1132         /* Run any generator sitting on the line */
1133         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1134                 /* Mask generator data temporarily */
1135                 void *tmp;
1136                 int res;
1137                 tmp = chan->generatordata;
1138                 chan->generatordata = NULL;
1139                 res = chan->generator->generate(chan, tmp, f->datalen, f->samples);
1140                 chan->generatordata = tmp;
1141                 if (res) {
1142                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1143                         ast_deactivate_generator(chan);
1144                 }
1145         }
1146         if (chan->fin & 0x80000000)
1147                 ast_frame_dump(chan->name, f, "<<");
1148         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1149                 chan->fin &= 0x80000000;
1150         else
1151                 chan->fin++;
1152         return f;
1153 }
1154
1155 int ast_indicate(struct ast_channel *chan, int condition)
1156 {
1157         int res = -1;
1158         /* Stop if we're a zombie or need a soft hangup */
1159         if (chan->zombie || ast_check_hangup(chan)) 
1160                 return -1;
1161         if (chan->pvt->indicate)
1162                 res = chan->pvt->indicate(chan, condition);
1163         if (!chan->pvt->indicate || res) {
1164                 /*
1165                  * Device does not support (that) indication, lets fake
1166                  * it by doing our own tone generation. (PM2002)
1167                  */
1168                 if (condition >= 0) {
1169                         const struct tone_zone_sound *ts = NULL;
1170                         switch (condition) {
1171                          case AST_CONTROL_RINGING:
1172                                 ts = ast_get_indication_tone(chan->zone, "ring");
1173                                 break;
1174                          case AST_CONTROL_BUSY:
1175                                 ts = ast_get_indication_tone(chan->zone, "busy");
1176                                 break;
1177                          case AST_CONTROL_CONGESTION:
1178                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1179                                 break;
1180                         }
1181                         if (ts && ts->data[0]) {
1182                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1183                                 ast_playtones_start(chan,0,ts->data, 1);
1184                         } else if (condition == AST_CONTROL_PROGRESS) {
1185                                 /* ast_playtones_stop(chan); */
1186                         } else {
1187                                 /* not handled */
1188                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1189                                 return -1;
1190                         }
1191                 }
1192                 else ast_playtones_stop(chan);
1193         }
1194         return 0;
1195 }
1196
1197 int ast_recvchar(struct ast_channel *chan, int timeout)
1198 {
1199         int res,ourto,c;
1200         struct ast_frame *f;
1201         
1202         ourto = timeout;
1203         for(;;)
1204            {
1205                 if (ast_check_hangup(chan)) return -1;
1206                 res = ast_waitfor(chan,ourto);
1207                 if (res <= 0) /* if timeout */
1208                    {
1209                         return 0;
1210                    }
1211                 ourto = res;
1212                 f = ast_read(chan);
1213                 if (f == NULL) return -1; /* if hangup */
1214                 if ((f->frametype == AST_FRAME_CONTROL) &&
1215                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1216                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1217                    {
1218                         c = *((char *)f->data);  /* get the data */
1219                         ast_frfree(f);
1220                         return(c);
1221                    }
1222                 ast_frfree(f);
1223         }
1224 }
1225
1226 int ast_sendtext(struct ast_channel *chan, char *text)
1227 {
1228         int res = 0;
1229         /* Stop if we're a zombie or need a soft hangup */
1230         if (chan->zombie || ast_check_hangup(chan)) 
1231                 return -1;
1232         CHECK_BLOCKING(chan);
1233         if (chan->pvt->send_text)
1234                 res = chan->pvt->send_text(chan, text);
1235         chan->blocking = 0;
1236         return res;
1237 }
1238
1239 static int do_senddigit(struct ast_channel *chan, char digit)
1240 {
1241         int res = -1;
1242
1243         if (chan->pvt->send_digit)
1244                 res = chan->pvt->send_digit(chan, digit);
1245         if (!chan->pvt->send_digit || res) {
1246                 /*
1247                  * Device does not support DTMF tones, lets fake
1248                  * it by doing our own generation. (PM2002)
1249                  */
1250                 static const char* dtmf_tones[] = {
1251                         "!941+1336/50,!0/50",   /* 0 */
1252                         "!697+1209/50,!0/50",   /* 1 */
1253                         "!697+1336/50,!0/50",   /* 2 */
1254                         "!697+1477/50,!0/50",   /* 3 */
1255                         "!770+1209/50,!0/50",   /* 4 */
1256                         "!770+1336/50,!0/50",   /* 5 */
1257                         "!770+1477/50,!0/50",   /* 6 */
1258                         "!852+1209/50,!0/50",   /* 7 */
1259                         "!852+1336/50,!0/50",   /* 8 */
1260                         "!852+1477/50,!0/50",   /* 9 */
1261                         "!697+1633/50,!0/50",   /* A */
1262                         "!770+1633/50,!0/50",   /* B */
1263                         "!852+1633/50,!0/50",   /* C */
1264                         "!941+1633/50,!0/50",   /* D */
1265                         "!941+1209/50,!0/50",   /* * */
1266                         "!941+1477/50,!0/50" }; /* # */
1267                 if (digit >= '0' && digit <='9')
1268                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1269                 else if (digit >= 'A' && digit <= 'D')
1270                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1271                 else if (digit == '*')
1272                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1273                 else if (digit == '#')
1274                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1275                 else {
1276                         /* not handled */
1277                         ast_log(LOG_WARNING, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1278                         return -1;
1279                 }
1280         }
1281         return 0;
1282 }
1283
1284 int ast_prod(struct ast_channel *chan)
1285 {
1286         struct ast_frame a = { AST_FRAME_VOICE };
1287         char nothing[128];
1288         /* Send an empty audio frame to get things moving */
1289         if (chan->_state != AST_STATE_UP) {
1290                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1291                 a.subclass = chan->pvt->rawwriteformat;
1292                 a.data = nothing + AST_FRIENDLY_OFFSET;
1293                 if (ast_write(chan, &a))
1294                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1295         }
1296         return 0;
1297 }
1298
1299 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1300 {
1301         int res;
1302         if (!chan->pvt->write_video)
1303                 return 0;
1304         res = ast_write(chan, fr);
1305         if (!res)
1306                 res = 1;
1307         return res;
1308 }
1309
1310 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1311 {
1312         int res = -1;
1313         struct ast_frame *f = NULL;
1314         /* Stop if we're a zombie or need a soft hangup */
1315         ast_pthread_mutex_lock(&chan->lock);
1316         if (chan->zombie || ast_check_hangup(chan))  {
1317                 ast_pthread_mutex_unlock(&chan->lock);
1318                 return -1;
1319         }
1320         /* Handle any pending masquerades */
1321         if (chan->masq) {
1322                 if (ast_do_masquerade(chan)) {
1323                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1324                         ast_pthread_mutex_unlock(&chan->lock);
1325                         return -1;
1326                 }
1327         }
1328         if (chan->masqr) {
1329                 ast_pthread_mutex_unlock(&chan->lock);
1330                 return 0;
1331         }
1332         if (chan->generatordata) {
1333                 if (chan->writeinterrupt)
1334                         ast_deactivate_generator(chan);
1335                 else {
1336                         ast_pthread_mutex_unlock(&chan->lock);
1337                         return 0;
1338                 }
1339         }
1340         if (chan->fout & 0x80000000)
1341                 ast_frame_dump(chan->name, fr, ">>");
1342         CHECK_BLOCKING(chan);
1343         switch(fr->frametype) {
1344         case AST_FRAME_CONTROL:
1345                 /* XXX Interpret control frames XXX */
1346                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1347                 break;
1348         case AST_FRAME_DTMF:
1349                 res = do_senddigit(chan,fr->subclass);
1350                 break;
1351         case AST_FRAME_TEXT:
1352                 if (chan->pvt->send_text)
1353                         res = chan->pvt->send_text(chan, (char *) fr->data);
1354                 break;
1355         case AST_FRAME_VIDEO:
1356                 /* XXX Handle translation of video codecs one day XXX */
1357                 if (chan->pvt->write_video)
1358                         res = chan->pvt->write_video(chan, fr);
1359                 else
1360                         res = 0;
1361                 break;
1362         default:
1363                 if (chan->pvt->write) {
1364                         if (chan->pvt->writetrans) {
1365                                 f = ast_translate(chan->pvt->writetrans, fr, 0);
1366                         } else
1367                                 f = fr;
1368                         if (f)  
1369                         {
1370                                 res = chan->pvt->write(chan, f);
1371                                 if( chan->monitor &&
1372                                                 chan->monitor->write_stream &&
1373                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1374                                         if( ast_writestream( chan->monitor->write_stream, f ) < 0 ) {
1375                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1376                                         }
1377                                 }
1378                         }
1379                         else
1380                                 res = 0;
1381                 }
1382         }
1383         if (f && (f != fr))
1384                 ast_frfree(f);
1385         chan->blocking = 0;
1386         /* Consider a write failure to force a soft hangup */
1387         if (res < 0)
1388                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1389         else {
1390                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1391                         chan->fout &= 0x80000000;
1392                 else
1393                         chan->fout++;
1394                 chan->fout++;
1395         }
1396         ast_pthread_mutex_unlock(&chan->lock);
1397         return res;
1398 }
1399
1400 int ast_set_write_format(struct ast_channel *chan, int fmts)
1401 {
1402         int fmt;
1403         int native;
1404         int res;
1405         
1406         native = chan->nativeformats;
1407         fmt = fmts;
1408         
1409         res = ast_translator_best_choice(&native, &fmt);
1410         if (res < 0) {
1411                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", fmts, chan->nativeformats);
1412                 return -1;
1413         }
1414         
1415         /* Now we have a good choice for both.  We'll write using our native format. */
1416         chan->pvt->rawwriteformat = native;
1417         /* User perspective is fmt */
1418         chan->writeformat = fmt;
1419         /* Free any write translation we have right now */
1420         if (chan->pvt->writetrans)
1421                 ast_translator_free_path(chan->pvt->writetrans);
1422         /* Build a translation path from the user write format to the raw writing format */
1423         chan->pvt->writetrans = ast_translator_build_path(chan->pvt->rawwriteformat, chan->writeformat);
1424         if (option_debug)
1425                 ast_log(LOG_DEBUG, "Set channel %s to write format %d\n", chan->name, chan->writeformat);
1426         return 0;
1427 }
1428
1429 int ast_set_read_format(struct ast_channel *chan, int fmts)
1430 {
1431         int fmt;
1432         int native;
1433         int res;
1434         
1435         native = chan->nativeformats;
1436         fmt = fmts;
1437         /* Find a translation path from the native read format to one of the user's read formats */
1438         res = ast_translator_best_choice(&fmt, &native);
1439         if (res < 0) {
1440                 ast_log(LOG_NOTICE, "Unable to find a path from %d to %d\n", chan->nativeformats, fmts);
1441                 return -1;
1442         }
1443         
1444         /* Now we have a good choice for both.  We'll write using our native format. */
1445         chan->pvt->rawreadformat = native;
1446         /* User perspective is fmt */
1447         chan->readformat = fmt;
1448         /* Free any read translation we have right now */
1449         if (chan->pvt->readtrans)
1450                 ast_translator_free_path(chan->pvt->readtrans);
1451         /* Build a translation path from the raw read format to the user reading format */
1452         chan->pvt->readtrans = ast_translator_build_path(chan->readformat, chan->pvt->rawreadformat);
1453         if (option_debug)
1454                 ast_log(LOG_DEBUG, "Set channel %s to read format %d\n", chan->name, chan->readformat);
1455         return 0;
1456 }
1457
1458 struct ast_channel *ast_request_and_dial(char *type, int format, void *data, int timeout, int *outstate, char *callerid)
1459 {
1460         int state = 0;
1461         struct ast_channel *chan;
1462         struct ast_frame *f;
1463         int res;
1464         
1465         chan = ast_request(type, format, data);
1466         if (chan) {
1467                 if (callerid)
1468                         ast_set_callerid(chan, callerid, 1);
1469                 if (!ast_call(chan, data, 0)) {
1470                         while(timeout && (chan->_state != AST_STATE_UP)) {
1471                                 res = ast_waitfor(chan, timeout);
1472                                 if (res < 0) {
1473                                         /* Something not cool, or timed out */
1474                                         ast_hangup(chan);
1475                                         chan = NULL;
1476                                         break;
1477                                 }
1478                                 /* If done, break out */
1479                                 if (!res)
1480                                         break;
1481                                 if (timeout > -1)
1482                                         timeout = res;
1483                                 f = ast_read(chan);
1484                                 if (!f) {
1485                                         state = AST_CONTROL_HANGUP;
1486                                         ast_hangup(chan);
1487                                         chan = NULL;
1488                                         break;
1489                                 }
1490                                 if (f->frametype == AST_FRAME_CONTROL) {
1491                                         if (f->subclass == AST_CONTROL_RINGING)
1492                                                 state = AST_CONTROL_RINGING;
1493                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1494                                                 state = f->subclass;
1495                                                 ast_frfree(f);
1496                                                 break;
1497                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1498                                                 state = f->subclass;
1499                                                 ast_frfree(f);
1500                                                 break;
1501                                         } else {
1502                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1503                                         }
1504                                 }
1505                                 ast_frfree(f);
1506                         }
1507                 } else {
1508                         ast_hangup(chan);
1509                         chan = NULL;
1510                         ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1511                 }
1512         } else
1513                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1514         if (chan && (chan->_state == AST_STATE_UP))
1515                 state = AST_CONTROL_ANSWER;
1516         if (outstate)
1517                 *outstate = state;
1518         return chan;
1519 }
1520
1521 struct ast_channel *ast_request(char *type, int format, void *data)
1522 {
1523         struct chanlist *chan;
1524         struct ast_channel *c = NULL;
1525         int capabilities;
1526         int fmt;
1527         int res;
1528         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1529                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1530                 return NULL;
1531         }
1532         chan = backends;
1533         while(chan) {
1534                 if (!strcasecmp(type, chan->type)) {
1535                         capabilities = chan->capabilities;
1536                         fmt = format;
1537                         res = ast_translator_best_choice(&fmt, &capabilities);
1538                         if (res < 0) {
1539                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->capabilities, format);
1540                                 PTHREAD_MUTEX_UNLOCK(&chlock);
1541                                 return NULL;
1542                         }
1543                         PTHREAD_MUTEX_UNLOCK(&chlock);
1544                         if (chan->requester)
1545                                 c = chan->requester(type, capabilities, data);
1546                         if (c) {
1547 //                              ast_device_state_changed(c->name);
1548                                 manager_event(EVENT_FLAG_CALL, "Newchannel",
1549                                 "Channel: %s\r\n"
1550                                 "State: %s\r\n"
1551                                 "Callerid: %s\r\n"
1552                                 "Uniqueid: %s\r\n",
1553                                 c->name, ast_state2str(c->_state), c->callerid ? c->callerid : "<unknown>", c->uniqueid);
1554                         }
1555                         return c;
1556                 }
1557                 chan = chan->next;
1558         }
1559         if (!chan)
1560                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1561         PTHREAD_MUTEX_UNLOCK(&chlock);
1562         return c;
1563 }
1564
1565 int ast_parse_device_state(char *device)
1566 {
1567         char name[AST_CHANNEL_NAME] = "";
1568         char *cut;
1569         struct ast_channel *chan;
1570
1571         chan = ast_channel_walk(NULL);
1572         while (chan) {
1573                 strncpy(name, chan->name, sizeof(name)-1);
1574                 cut = strchr(name,'-');
1575                 if (cut)
1576                         *cut = 0;
1577                 if (!strcmp(name, device))
1578                         return AST_DEVICE_INUSE;
1579                 chan = ast_channel_walk(chan);
1580         }
1581         return AST_DEVICE_UNKNOWN;
1582 }
1583
1584 int ast_device_state(char *device)
1585 {
1586         char tech[AST_MAX_EXTENSION] = "";
1587         char *number;
1588         struct chanlist *chanls;
1589         int res = 0;
1590         
1591         strncpy(tech, device, sizeof(tech)-1);
1592         number = strchr(tech, '/');
1593         if (!number) {
1594             return AST_DEVICE_INVALID;
1595         }
1596         *number = 0;
1597         number++;
1598                 
1599         if (PTHREAD_MUTEX_LOCK(&chlock)) {
1600                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1601                 return -1;
1602         }
1603         chanls = backends;
1604         while(chanls) {
1605                 if (!strcasecmp(tech, chanls->type)) {
1606                         PTHREAD_MUTEX_UNLOCK(&chlock);
1607                         if (!chanls->devicestate) 
1608                                 return ast_parse_device_state(device);
1609                         else {
1610                                 res = chanls->devicestate(number);
1611                                 if (res == AST_DEVICE_UNKNOWN)
1612                                         return ast_parse_device_state(device);
1613                                 else
1614                                         return res;
1615                         }
1616                 }
1617                 chanls = chanls->next;
1618         }
1619         PTHREAD_MUTEX_UNLOCK(&chlock);
1620         return AST_DEVICE_INVALID;
1621 }
1622
1623 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
1624 {
1625         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1626            If the remote end does not answer within the timeout, then do NOT hang up, but 
1627            return anyway.  */
1628         int res = -1;
1629         /* Stop if we're a zombie or need a soft hangup */
1630         ast_pthread_mutex_lock(&chan->lock);
1631         if (!chan->zombie && !ast_check_hangup(chan)) 
1632                 if (chan->pvt->call)
1633                         res = chan->pvt->call(chan, addr, timeout);
1634         pthread_mutex_unlock(&chan->lock);
1635         return res;
1636 }
1637
1638 int ast_transfer(struct ast_channel *chan, char *dest) 
1639 {
1640         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
1641            If the remote end does not answer within the timeout, then do NOT hang up, but 
1642            return anyway.  */
1643         int res = -1;
1644         /* Stop if we're a zombie or need a soft hangup */
1645         ast_pthread_mutex_lock(&chan->lock);
1646         if (!chan->zombie && !ast_check_hangup(chan)) {
1647                 if (chan->pvt->transfer) {
1648                         res = chan->pvt->transfer(chan, dest);
1649                         if (!res)
1650                                 res = 1;
1651                 } else
1652                         res = 0;
1653         }
1654         pthread_mutex_unlock(&chan->lock);
1655         return res;
1656 }
1657
1658 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
1659 {
1660         int pos=0;
1661         int to = ftimeout;
1662         char d;
1663         /* XXX Merge with full version? XXX */
1664         /* Stop if we're a zombie or need a soft hangup */
1665         if (c->zombie || ast_check_hangup(c)) 
1666                 return -1;
1667         if (!len)
1668                 return -1;
1669         do {
1670                 if (c->stream) {
1671                         d = ast_waitstream(c, AST_DIGIT_ANY);
1672                         ast_stopstream(c);
1673                         usleep(1000);
1674                         if (!d)
1675                                 d = ast_waitfordigit(c, to);
1676                 } else {
1677                         d = ast_waitfordigit(c, to);
1678                 }
1679                 if (d < 0)
1680                         return -1;
1681                 if (d == 0) {
1682                         s[pos]='\0';
1683                         return 1;
1684                 }
1685                 if (!strchr(enders, d))
1686                         s[pos++] = d;
1687                 if (strchr(enders, d) || (pos >= len)) {
1688                         s[pos]='\0';
1689                         return 0;
1690                 }
1691                 to = timeout;
1692         } while(1);
1693         /* Never reached */
1694         return 0;
1695 }
1696
1697 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
1698 {
1699         int pos=0;
1700         int to = ftimeout;
1701         char d;
1702         /* Stop if we're a zombie or need a soft hangup */
1703         if (c->zombie || ast_check_hangup(c)) 
1704                 return -1;
1705         if (!len)
1706                 return -1;
1707         do {
1708                 if (c->stream) {
1709                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
1710                         ast_stopstream(c);
1711                         usleep(1000);
1712                         if (!d)
1713                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1714                 } else {
1715                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
1716                 }
1717                 if (d < 0)
1718                         return -1;
1719                 if (d == 0) {
1720                         s[pos]='\0';
1721                         return 1;
1722                 }
1723                 if (d == 1) {
1724                         s[pos]='\0';
1725                         return 2;
1726                 }
1727                 if (!strchr(enders, d))
1728                         s[pos++] = d;
1729                 if (strchr(enders, d) || (pos >= len)) {
1730                         s[pos]='\0';
1731                         return 0;
1732                 }
1733                 to = timeout;
1734         } while(1);
1735         /* Never reached */
1736         return 0;
1737 }
1738
1739 int ast_channel_supports_html(struct ast_channel *chan)
1740 {
1741         if (chan->pvt->send_html)
1742                 return 1;
1743         return 0;
1744 }
1745
1746 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
1747 {
1748         if (chan->pvt->send_html)
1749                 return chan->pvt->send_html(chan, subclass, data, datalen);
1750         return -1;
1751 }
1752
1753 int ast_channel_sendurl(struct ast_channel *chan, char *url)
1754 {
1755         if (chan->pvt->send_html)
1756                 return chan->pvt->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
1757         return -1;
1758 }
1759
1760 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
1761 {
1762         int peerf;
1763         int chanf;
1764         int res;
1765         peerf = peer->nativeformats;
1766         chanf = chan->nativeformats;
1767         res = ast_translator_best_choice(&peerf, &chanf);
1768         if (res < 0) {
1769                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
1770                 return -1;
1771         }
1772         /* Set read format on channel */
1773         res = ast_set_read_format(chan, peerf);
1774         if (res < 0) {
1775                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
1776                 return -1;
1777         }
1778         /* Set write format on peer channel */
1779         res = ast_set_write_format(peer, peerf);
1780         if (res < 0) {
1781                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
1782                 return -1;
1783         }
1784         /* Now we go the other way */
1785         peerf = peer->nativeformats;
1786         chanf = chan->nativeformats;
1787         res = ast_translator_best_choice(&chanf, &peerf);
1788         if (res < 0) {
1789                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
1790                 return -1;
1791         }
1792         /* Set writeformat on channel */
1793         res = ast_set_write_format(chan, chanf);
1794         if (res < 0) {
1795                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
1796                 return -1;
1797         }
1798         /* Set read format on peer channel */
1799         res = ast_set_read_format(peer, chanf);
1800         if (res < 0) {
1801                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
1802                 return -1;
1803         }
1804         return 0;
1805 }
1806
1807 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
1808 {
1809         struct ast_frame null = { AST_FRAME_NULL, };
1810         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
1811                 clone->name, original->name);
1812         if (original->masq) {
1813                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1814                         original->masq->name, original->name);
1815                 return -1;
1816         }
1817         if (clone->masqr) {
1818                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
1819                         clone->name, clone->masqr->name);
1820                 return -1;
1821         }
1822         original->masq = clone;
1823         clone->masqr = original;
1824         /* XXX can't really hold the lock here, but at the same time, it' s
1825            not really safe not to XXX */
1826         ast_queue_frame(original, &null, 0);
1827         ast_queue_frame(clone, &null, 0);
1828         ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
1829         return 0;
1830 }
1831
1832 void ast_change_name(struct ast_channel *chan, char *newname)
1833 {
1834         char tmp[256];
1835         strncpy(tmp, chan->name, 256);
1836         strncpy(chan->name, newname, sizeof(chan->name) - 1);
1837         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
1838 }
1839
1840 static int ast_do_masquerade(struct ast_channel *original)
1841 {
1842         int x;
1843         int res=0;
1844         char *tmp;
1845         void *tmpv;
1846         struct ast_channel_pvt *p;
1847         struct ast_channel *clone = original->masq;
1848         int rformat = original->readformat;
1849         int wformat = original->writeformat;
1850         char newn[100];
1851         char orig[100];
1852         char masqn[100];
1853         char zombn[100];
1854         
1855 #if 1
1856         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
1857                 clone->name, clone->_state, original->name, original->_state);
1858 #endif
1859         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
1860            the clone channel into the original channel.  Start by killing off the original
1861            channel's backend.   I'm not sure we're going to keep this function, because 
1862            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
1863
1864         /* Having remembered the original read/write formats, we turn off any translation on either
1865            one */
1866         free_translation(clone);
1867         free_translation(original);
1868
1869         /* We need the clone's lock, too */
1870         ast_pthread_mutex_lock(&clone->lock);
1871
1872         /* Unlink the masquerade */
1873         original->masq = NULL;
1874         clone->masqr = NULL;
1875         
1876         /* Save the original name */
1877         strncpy(orig, original->name, sizeof(orig) - 1);
1878         /* Save the new name */
1879         strncpy(newn, clone->name, sizeof(newn) - 1);
1880         /* Create the masq name */
1881         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
1882                 
1883         /* Copy the name from the clone channel */
1884         strncpy(original->name, newn, sizeof(original->name)-1);
1885
1886         /* Mangle the name of the clone channel */
1887         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
1888         
1889         /* Notify any managers of the change, first the masq then the other */
1890         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", newn, masqn);
1891         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", orig, newn);
1892
1893         /* Swap the guts */     
1894         p = original->pvt;
1895         original->pvt = clone->pvt;
1896         clone->pvt = p;
1897         
1898         clone->_softhangup = AST_SOFTHANGUP_DEV;
1899
1900
1901         if (clone->pvt->fixup){
1902                 res = clone->pvt->fixup(original, clone);
1903                 if (res) 
1904                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
1905         }
1906
1907         /* Start by disconnecting the original's physical side */
1908         if (clone->pvt->hangup)
1909                 res = clone->pvt->hangup(clone);
1910         if (res) {
1911                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
1912                 pthread_mutex_unlock(&clone->lock);
1913                 return -1;
1914         }
1915         
1916         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
1917         /* Mangle the name of the clone channel */
1918         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
1919         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\n", masqn, zombn);
1920
1921         /* Keep the same language.  */
1922         /* Update the type. */
1923         original->type = clone->type;
1924         /* Copy the FD's */
1925         for (x=0;x<AST_MAX_FDS;x++) {
1926                 original->fds[x] = clone->fds[x];
1927         }
1928         /* Move the variables */
1929         tmpv = original->varshead.first;
1930         original->varshead.first = clone->varshead.first;
1931         clone->varshead.first = tmpv;
1932         /* Presense of ADSI capable CPE follows clone */
1933         original->adsicpe = clone->adsicpe;
1934         /* Bridge remains the same */
1935         /* CDR fields remain the same */
1936         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
1937         /* Application and data remain the same */
1938         /* Clone exception  becomes real one, as with fdno */
1939         original->exception = clone->exception;
1940         original->fdno = clone->fdno;
1941         /* Schedule context remains the same */
1942         /* Stream stuff stays the same */
1943         /* Keep the original state.  The fixup code will need to work with it most likely */
1944
1945         /* dnid and callerid change to become the new, HOWEVER, we also link the original's
1946            fields back into the defunct 'clone' so that they will be freed when
1947            ast_frfree is eventually called */
1948         tmp = original->dnid;
1949         original->dnid = clone->dnid;
1950         clone->dnid = tmp;
1951         
1952         tmp = original->callerid;
1953         original->callerid = clone->callerid;
1954         clone->callerid = tmp;
1955         
1956         /* Restore original timing file descriptor */
1957         original->fds[AST_MAX_FDS - 2] = original->timingfd;
1958         
1959         /* Our native formats are different now */
1960         original->nativeformats = clone->nativeformats;
1961
1962         /* And of course, so does our current state.  Note we need not
1963            call ast_setstate since the event manager doesn't really consider
1964            these separate */
1965         original->_state = clone->_state;
1966         
1967         /* Context, extension, priority, app data, jump table,  remain the same */
1968         /* pvt switches.  pbx stays the same, as does next */
1969         
1970         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
1971            a zombie so nothing tries to touch it.  If it's already been marked as a
1972            zombie, then free it now (since it already is considered invalid). */
1973         if (clone->zombie) {
1974                 pthread_mutex_unlock(&clone->lock);
1975                 ast_channel_free(clone);
1976                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
1977         } else {
1978                 clone->zombie=1;
1979                 pthread_mutex_unlock(&clone->lock);
1980         }
1981         /* Set the write format */
1982         ast_set_write_format(original, wformat);
1983
1984         /* Set the read format */
1985         ast_set_read_format(original, rformat);
1986
1987         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
1988
1989         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
1990            can fix up everything as best as possible */
1991         if (original->pvt->fixup) {
1992                 res = original->pvt->fixup(clone, original);
1993                 if (res) {
1994                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
1995                                 original->type, original->name);
1996                         return -1;
1997                 }
1998         } else
1999                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2000                         original->type, original->name);
2001         /* Signal any blocker */
2002         if (original->blocking)
2003                 pthread_kill(original->blocker, SIGURG);
2004         return 0;
2005 }
2006
2007 void ast_set_callerid(struct ast_channel *chan, char *callerid, int anitoo)
2008 {
2009         if (chan->callerid)
2010                 free(chan->callerid);
2011         if (anitoo && chan->ani)
2012                 free(chan->ani);
2013         if (callerid) {
2014                 chan->callerid = strdup(callerid);
2015                 if (anitoo)
2016                         chan->ani = strdup(callerid);
2017         } else {
2018                 chan->callerid = NULL;
2019                 if (anitoo)
2020                         chan->ani = NULL;
2021         }
2022         if (chan->cdr)
2023                 ast_cdr_setcid(chan->cdr, chan);
2024         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2025                                 "Channel: %s\r\n"
2026                                 "Callerid: %s\r\n"
2027                                 "Uniqueid: %s\r\n",
2028                                 chan->name, chan->callerid ? 
2029                                 chan->callerid : "<Unknown>",
2030                                 chan->uniqueid);
2031 }
2032
2033 int ast_setstate(struct ast_channel *chan, int state)
2034 {
2035         if (chan->_state != state) {
2036                 int oldstate = chan->_state;
2037                 chan->_state = state;
2038                 if (oldstate == AST_STATE_DOWN) {
2039                         ast_device_state_changed(chan->name);
2040                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2041                         "Channel: %s\r\n"
2042                         "State: %s\r\n"
2043                         "Callerid: %s\r\n"
2044                         "Uniqueid: %s\r\n",
2045                         chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2046                 } else {
2047                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2048                                 "Channel: %s\r\n"
2049                                 "State: %s\r\n"
2050                                 "Callerid: %s\r\n"
2051                                 "Uniqueid: %s\r\n",
2052                                 chan->name, ast_state2str(chan->_state), chan->callerid ? chan->callerid : "<unknown>", chan->uniqueid);
2053                 }
2054         }
2055         return 0;
2056 }
2057
2058 int ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2059 {
2060         /* Copy voice back and forth between the two channels.  Give the peer
2061            the ability to transfer calls with '#<extension' syntax. */
2062         struct ast_channel *cs[3];
2063         int to = -1;
2064         struct ast_frame *f;
2065         struct ast_channel *who = NULL;
2066         int res;
2067         int nativefailed=0;
2068
2069         /* Stop if we're a zombie or need a soft hangup */
2070         if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) 
2071                 return -1;
2072         if (c0->bridge) {
2073                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2074                         c0->name, c0->bridge->name);
2075                 return -1;
2076         }
2077         if (c1->bridge) {
2078                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2079                         c1->name, c1->bridge->name);
2080                 return -1;
2081         }
2082         
2083         /* Keep track of bridge */
2084         c0->bridge = c1;
2085         c1->bridge = c0;
2086         cs[0] = c0;
2087         cs[1] = c1;
2088         
2089         manager_event(EVENT_FLAG_CALL, "Link", 
2090                         "Channel1: %s\r\n"
2091                         "Channel2: %s\r\n",
2092                         c0->name, c1->name);
2093
2094         for (/* ever */;;) {
2095                 /* Stop if we're a zombie or need a soft hangup */
2096                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
2097                         *fo = NULL;
2098                         if (who) *rc = who;
2099                         res = 0;
2100                         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");
2101                         break;
2102                 }
2103                 if (c0->pvt->bridge && 
2104                         (c0->pvt->bridge == c1->pvt->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2105                                 /* Looks like they share a bridge code */
2106                         if (option_verbose > 2) 
2107                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2108                         if (!(res = c0->pvt->bridge(c0, c1, flags, fo, rc))) {
2109                                 c0->bridge = NULL;
2110                                 c1->bridge = NULL;
2111                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2112                                         "Channel1: %s\r\n"
2113                                         "Channel2: %s\r\n",
2114                                         c0->name, c1->name);
2115                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2116                                 return 0;
2117                         }
2118                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2119                            my not wanting to bridge */
2120                         if ((res != -2) && (res != -3))
2121                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2122                         if (res != -3) nativefailed++;
2123                 }
2124         
2125                         
2126                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat)) &&
2127                         !(c0->generator || c1->generator))  {
2128                         if (ast_channel_make_compatible(c0, c1)) {
2129                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2130                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2131                                         "Channel1: %s\r\n"
2132                                         "Channel2: %s\r\n",
2133                                         c0->name, c1->name);
2134                                 return -1;
2135                         }
2136                 }
2137                 who = ast_waitfor_n(cs, 2, &to);
2138                 if (!who) {
2139                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2140                         continue;
2141                 }
2142                 f = ast_read(who);
2143                 if (!f) {
2144                         *fo = NULL;
2145                         *rc = who;
2146                         res = 0;
2147                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2148                         break;
2149                 }
2150
2151                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
2152                         *fo = f;
2153                         *rc = who;
2154                         res =  0;
2155                         ast_log(LOG_DEBUG, "Got a FRAME_CONTROL frame on channel %s\n",who->name);
2156                         break;
2157                 }
2158                 if ((f->frametype == AST_FRAME_VOICE) ||
2159                         (f->frametype == AST_FRAME_TEXT) ||
2160                         (f->frametype == AST_FRAME_VIDEO) || 
2161                         (f->frametype == AST_FRAME_IMAGE) ||
2162                         (f->frametype == AST_FRAME_DTMF)) {
2163                         if ((f->frametype == AST_FRAME_DTMF) && 
2164                                 (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2165                                 if ((who == c0)) {
2166                                         if  ((flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2167                                                 *rc = c0;
2168                                                 *fo = f;
2169                                                 /* Take out of conference mode */
2170                                                 res = 0;
2171                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2172                                                 break;
2173                                         } else 
2174                                                 goto tackygoto;
2175                                 } else
2176                                 if ((who == c1)) {
2177                                         if (flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2178                                                 *rc = c1;
2179                                                 *fo = f;
2180                                                 res =  0;
2181                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2182                                                 break;
2183                                         } else
2184                                                 goto tackygoto;
2185                                 }
2186                         } else {
2187 #if 0
2188                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2189                                 if (who == last) 
2190                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2191                                 last = who;
2192 #endif
2193 tackygoto:
2194                                 /* Don't copy packets if there is a generator on either one, since they're
2195                                    not supposed to be listening anyway */
2196                                 if (who == c0) 
2197                                         ast_write(c1, f);
2198                                 else 
2199                                         ast_write(c0, f);
2200                         }
2201                         ast_frfree(f);
2202                 } else
2203                         ast_frfree(f);
2204                 /* Swap who gets priority */
2205                 cs[2] = cs[0];
2206                 cs[0] = cs[1];
2207                 cs[1] = cs[2];
2208         }
2209         c0->bridge = NULL;
2210         c1->bridge = NULL;
2211         manager_event(EVENT_FLAG_CALL, "Unlink", 
2212                                         "Channel1: %s\r\n"
2213                                         "Channel2: %s\r\n",
2214                                         c0->name, c1->name);
2215         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2216         return res;
2217 }
2218
2219 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2220 {
2221         int res;
2222         if (chan->pvt->setoption) {
2223                 res = chan->pvt->setoption(chan, option, data, datalen);
2224                 if (res < 0)
2225                         return res;
2226         } else {
2227                 errno = ENOSYS;
2228                 return -1;
2229         }
2230         if (block) {
2231                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2232                    intermediate packets. XXX */
2233                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2234                 return -1;
2235         }
2236         return 0;
2237 }
2238
2239 struct tonepair_def {
2240         int freq1;
2241         int freq2;
2242         int duration;
2243         int vol;
2244 };
2245
2246 struct tonepair_state {
2247         float freq1;
2248         float freq2;
2249         float vol;
2250         int duration;
2251         int pos;
2252         int origwfmt;
2253         struct ast_frame f;
2254         unsigned char offset[AST_FRIENDLY_OFFSET];
2255         short data[4000];
2256 };
2257
2258 static void tonepair_release(struct ast_channel *chan, void *params)
2259 {
2260         struct tonepair_state *ts = params;
2261         if (chan) {
2262                 ast_set_write_format(chan, ts->origwfmt);
2263         }
2264         free(ts);
2265 }
2266
2267 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2268 {
2269         struct tonepair_state *ts;
2270         struct tonepair_def *td = params;
2271         ts = malloc(sizeof(struct tonepair_state));
2272         if (!ts)
2273                 return NULL;
2274         memset(ts, 0, sizeof(struct tonepair_state));
2275         ts->origwfmt = chan->writeformat;
2276         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2277                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2278                 tonepair_release(NULL, ts);
2279                 ts = NULL;
2280         } else {
2281                 ts->freq1 = td->freq1;
2282                 ts->freq2 = td->freq2;
2283                 ts->duration = td->duration;
2284                 ts->vol = td->vol;
2285         }
2286         /* Let interrupts interrupt :) */
2287         chan->writeinterrupt = 1;
2288         return ts;
2289 }
2290
2291 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2292 {
2293         struct tonepair_state *ts = data;
2294         int x;
2295
2296         /* we need to prepare a frame with 16 * timelen samples as we're 
2297          * generating SLIN audio
2298          */
2299         len = samples * 2;
2300
2301         if (len > sizeof(ts->data) / 2 - 1) {
2302                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
2303                 return -1;
2304         }
2305         memset(&ts->f, 0, sizeof(ts->f));
2306         for (x=0;x<len/2;x++) {
2307                 ts->data[x] = ts->vol * (
2308                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
2309                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
2310                         );
2311         }
2312         ts->f.frametype = AST_FRAME_VOICE;
2313         ts->f.subclass = AST_FORMAT_SLINEAR;
2314         ts->f.datalen = len;
2315         ts->f.samples = samples;
2316         ts->f.offset = AST_FRIENDLY_OFFSET;
2317         ts->f.data = ts->data;
2318         ast_write(chan, &ts->f);
2319         ts->pos += x;
2320         if (ts->duration > 0) {
2321                 if (ts->pos >= ts->duration * 8)
2322                         return -1;
2323         }
2324         return 0;
2325 }
2326
2327 static struct ast_generator tonepair = {
2328         alloc: tonepair_alloc,
2329         release: tonepair_release,
2330         generate: tonepair_generator,
2331 };
2332
2333 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2334 {
2335         struct tonepair_def d = { 0, };
2336         d.freq1 = freq1;
2337         d.freq2 = freq2;
2338         d.duration = duration;
2339         if (vol < 1)
2340                 d.vol = 8192;
2341         else
2342                 d.vol = vol;
2343         if (ast_activate_generator(chan, &tonepair, &d))
2344                 return -1;
2345         return 0;
2346 }
2347
2348 void ast_tonepair_stop(struct ast_channel *chan)
2349 {
2350         ast_deactivate_generator(chan);
2351 }
2352
2353 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
2354 {
2355         struct ast_frame *f;
2356         int res;
2357         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
2358                 return res;
2359
2360         /* Give us some wiggle room */
2361         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
2362                 f = ast_read(chan);
2363                 if (f)
2364                         ast_frfree(f);
2365                 else
2366                         return -1;
2367         }
2368         return 0;
2369 }
2370
2371