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