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