silly typo
[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                         if (errno == EINTR)
1177                                 continue;
1178                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1179                         return -1;
1180                 } else if (outfd > -1) {
1181                         /* The FD we were watching has something waiting */
1182                         return 1;
1183                 } else if (rchan) {
1184                         f = ast_read(c);
1185                         if(!f) {
1186                                 return -1;
1187                         }
1188
1189                         switch(f->frametype) {
1190                         case AST_FRAME_DTMF:
1191                                 res = f->subclass;
1192                                 ast_frfree(f);
1193                                 return res;
1194                         case AST_FRAME_CONTROL:
1195                                 switch(f->subclass) {
1196                                 case AST_CONTROL_HANGUP:
1197                                         ast_frfree(f);
1198                                         return -1;
1199                                 case AST_CONTROL_RINGING:
1200                                 case AST_CONTROL_ANSWER:
1201                                         /* Unimportant */
1202                                         break;
1203                                 default:
1204                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1205                                 }
1206                         case AST_FRAME_VOICE:
1207                                 /* Write audio if appropriate */
1208                                 if (audiofd > -1)
1209                                         write(audiofd, f->data, f->datalen);
1210                         }
1211                         /* Ignore */
1212                         ast_frfree(f);
1213                 }
1214         }
1215         return 0; /* Time is up */
1216 }
1217
1218 struct ast_frame *ast_read(struct ast_channel *chan)
1219 {
1220         struct ast_frame *f = NULL;
1221         int blah;
1222 #ifdef ZAPTEL_OPTIMIZATIONS
1223         int (*func)(void *);
1224         void *data;
1225         int res;
1226 #endif
1227         static struct ast_frame null_frame = 
1228         {
1229                 AST_FRAME_NULL,
1230         };
1231         
1232         ast_mutex_lock(&chan->lock);
1233         if (chan->masq) {
1234                 if (ast_do_masquerade(chan)) {
1235                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1236                         f = NULL;
1237                 } else
1238                         f =  &null_frame;
1239                 ast_mutex_unlock(&chan->lock);
1240                 return f;
1241         }
1242
1243         /* Stop if we're a zombie or need a soft hangup */
1244         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1245                 if (chan->generator)
1246                         ast_deactivate_generator(chan);
1247                 ast_mutex_unlock(&chan->lock);
1248                 return NULL;
1249         }
1250
1251         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1252                 /* We have DTMF that has been deferred.  Return it now */
1253                 chan->dtmff.frametype = AST_FRAME_DTMF;
1254                 chan->dtmff.subclass = chan->dtmfq[0];
1255                 /* Drop first digit */
1256                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1257                 ast_mutex_unlock(&chan->lock);
1258                 return &chan->dtmff;
1259         }
1260         
1261         /* Read and ignore anything on the alertpipe, but read only
1262            one sizeof(blah) per frame that we send from it */
1263         if (chan->alertpipe[0] > -1) {
1264                 read(chan->alertpipe[0], &blah, sizeof(blah));
1265         }
1266 #ifdef ZAPTEL_OPTIMIZATIONS
1267         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1268                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1269                 blah = -1;
1270                 /* IF we can't get event, assume it's an expired as-per the old interface */
1271                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1272                 if (res) 
1273                         blah = ZT_EVENT_TIMER_EXPIRED;
1274
1275                 if (blah == ZT_EVENT_TIMER_PING) {
1276 #if 0
1277                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1278 #endif                  
1279                         if (!chan->readq || !chan->readq->next) {
1280                                 /* Acknowledge PONG unless we need it again */
1281 #if 0
1282                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1283 #endif                          
1284                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1285                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1286                                 }
1287                         }
1288                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1289                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1290                         func = chan->timingfunc;
1291                         data = chan->timingdata;
1292                         ast_mutex_unlock(&chan->lock);
1293                         if (func) {
1294 #if 0
1295                                 ast_log(LOG_DEBUG, "Calling private function\n");
1296 #endif                  
1297                                 func(data);
1298                         } else {
1299                                 blah = 0;
1300                                 ast_mutex_lock(&chan->lock);
1301                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1302                                 chan->timingdata = NULL;
1303                                 ast_mutex_unlock(&chan->lock);
1304                         }
1305                         f =  &null_frame;
1306                         return f;
1307                 } else
1308                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1309         }
1310 #endif
1311         /* Check for pending read queue */
1312         if (chan->readq) {
1313                 f = chan->readq;
1314                 chan->readq = f->next;
1315                 /* Interpret hangup and return NULL */
1316                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1317                         ast_frfree(f);
1318                         f = NULL;
1319                 }
1320         } else {
1321                 chan->blocker = pthread_self();
1322                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1323                         if (chan->tech->exception) 
1324                                 f = chan->tech->exception(chan);
1325                         else {
1326                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1327                                 f = &null_frame;
1328                         }
1329                         /* Clear the exception flag */
1330                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1331                 } else
1332                 if (chan->tech->read)
1333                         f = chan->tech->read(chan);
1334                 else
1335                         ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1336         }
1337
1338
1339         if (f && (f->frametype == AST_FRAME_VOICE)) {
1340                 if (!(f->subclass & chan->nativeformats)) {
1341                         /* This frame can't be from the current native formats -- drop it on the
1342                            floor */
1343                         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));
1344                         ast_frfree(f);
1345                         f = &null_frame;
1346                 } else {
1347                         if (chan->monitor && chan->monitor->read_stream ) {
1348 #ifndef MONITOR_CONSTANT_DELAY
1349                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1350                                 if (jump >= 0) {
1351                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1352                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1353                                         chan->insmpl += jump + 2 * f->samples;
1354                                 } else
1355                                         chan->insmpl+= f->samples;
1356 #else
1357                                 int jump = chan->outsmpl - chan->insmpl;
1358                                 if (jump - MONITOR_DELAY >= 0) {
1359                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1360                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1361                                         chan->insmpl += jump;
1362                                 } else
1363                                         chan->insmpl += f->samples;
1364 #endif
1365                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1366                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1367                         }
1368                         if (chan->readtrans) {
1369                                 f = ast_translate(chan->readtrans, f, 1);
1370                                 if (!f)
1371                                         f = &null_frame;
1372                         }
1373                 }
1374         }
1375
1376         /* Make sure we always return NULL in the future */
1377         if (!f) {
1378                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1379                 if (chan->generator)
1380                         ast_deactivate_generator(chan);
1381                 /* End the CDR if appropriate */
1382                 if (chan->cdr)
1383                         ast_cdr_end(chan->cdr);
1384         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1385                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1386                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1387                 else
1388                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1389                 f = &null_frame;
1390         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1391                 if (chan->_state == AST_STATE_UP) {
1392                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1393                         f = &null_frame;
1394                 }
1395                 /* Answer the CDR */
1396                 ast_setstate(chan, AST_STATE_UP);
1397                 ast_cdr_answer(chan->cdr);
1398         } 
1399
1400         /* Run any generator sitting on the line */
1401         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1402                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1403                    will be calling the generator instead */
1404                 void *tmp;
1405                 int res;
1406                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1407                 if (chan->timingfunc) {
1408                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1409                         ast_settimeout(chan, 0, NULL, NULL);
1410                 }
1411                 tmp = chan->generatordata;
1412                 chan->generatordata = NULL;
1413                 generate = chan->generator->generate;
1414                 res = generate(chan, tmp, f->datalen, f->samples);
1415                 chan->generatordata = tmp;
1416                 if (res) {
1417                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1418                         ast_deactivate_generator(chan);
1419                 }
1420         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1421                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1422                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1423                         ast_settimeout(chan, 160, generator_force, chan);
1424                 }
1425         }
1426         if (chan->fin & 0x80000000)
1427                 ast_frame_dump(chan->name, f, "<<");
1428         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1429                 chan->fin &= 0x80000000;
1430         else
1431                 chan->fin++;
1432         ast_mutex_unlock(&chan->lock);
1433         return f;
1434 }
1435
1436 int ast_indicate(struct ast_channel *chan, int condition)
1437 {
1438         int res = -1;
1439         /* Stop if we're a zombie or need a soft hangup */
1440         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1441                 return -1;
1442         ast_mutex_lock(&chan->lock);
1443         if (chan->tech->indicate)
1444                 res = chan->tech->indicate(chan, condition);
1445         ast_mutex_unlock(&chan->lock);
1446         if (!chan->tech->indicate || res) {
1447                 /*
1448                  * Device does not support (that) indication, lets fake
1449                  * it by doing our own tone generation. (PM2002)
1450                  */
1451                 if (condition >= 0) {
1452                         const struct tone_zone_sound *ts = NULL;
1453                         switch (condition) {
1454                          case AST_CONTROL_RINGING:
1455                                 ts = ast_get_indication_tone(chan->zone, "ring");
1456                                 break;
1457                          case AST_CONTROL_BUSY:
1458                                 ts = ast_get_indication_tone(chan->zone, "busy");
1459                                 break;
1460                          case AST_CONTROL_CONGESTION:
1461                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1462                                 break;
1463                         }
1464                         if (ts && ts->data[0]) {
1465                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1466                                 ast_playtones_start(chan,0,ts->data, 1);
1467                                 res = 0;
1468                         } else if (condition == AST_CONTROL_PROGRESS) {
1469                                 /* ast_playtones_stop(chan); */
1470                         } else if (condition == AST_CONTROL_PROCEEDING) {
1471                                 /* Do nothing, really */
1472                         } else if (condition == AST_CONTROL_HOLD) {
1473                                 /* Do nothing.... */
1474                         } else if (condition == AST_CONTROL_UNHOLD) {
1475                                 /* Do nothing.... */
1476                         } else {
1477                                 /* not handled */
1478                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1479                                 res = -1;
1480                         }
1481                 }
1482                 else ast_playtones_stop(chan);
1483         }
1484         return res;
1485 }
1486
1487 int ast_recvchar(struct ast_channel *chan, int timeout)
1488 {
1489         int res,ourto,c;
1490         struct ast_frame *f;
1491         
1492         ourto = timeout;
1493         for(;;)
1494            {
1495                 if (ast_check_hangup(chan)) return -1;
1496                 res = ast_waitfor(chan,ourto);
1497                 if (res <= 0) /* if timeout */
1498                    {
1499                         return 0;
1500                    }
1501                 ourto = res;
1502                 f = ast_read(chan);
1503                 if (f == NULL) return -1; /* if hangup */
1504                 if ((f->frametype == AST_FRAME_CONTROL) &&
1505                     (f->subclass == AST_CONTROL_HANGUP)) return -1; /* if hangup */
1506                 if (f->frametype == AST_FRAME_TEXT)  /* if a text frame */
1507                    {
1508                         c = *((char *)f->data);  /* get the data */
1509                         ast_frfree(f);
1510                         return(c);
1511                    }
1512                 ast_frfree(f);
1513         }
1514 }
1515
1516 int ast_sendtext(struct ast_channel *chan, char *text)
1517 {
1518         int res = 0;
1519         /* Stop if we're a zombie or need a soft hangup */
1520         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1521                 return -1;
1522         CHECK_BLOCKING(chan);
1523         if (chan->tech->send_text)
1524                 res = chan->tech->send_text(chan, text);
1525         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1526         return res;
1527 }
1528
1529 static int do_senddigit(struct ast_channel *chan, char digit)
1530 {
1531         int res = -1;
1532
1533         if (chan->tech->send_digit)
1534                 res = chan->tech->send_digit(chan, digit);
1535         if (!chan->tech->send_digit || res) {
1536                 /*
1537                  * Device does not support DTMF tones, lets fake
1538                  * it by doing our own generation. (PM2002)
1539                  */
1540                 static const char* dtmf_tones[] = {
1541                         "!941+1336/100,!0/100", /* 0 */
1542                         "!697+1209/100,!0/100", /* 1 */
1543                         "!697+1336/100,!0/100", /* 2 */
1544                         "!697+1477/100,!0/100", /* 3 */
1545                         "!770+1209/100,!0/100", /* 4 */
1546                         "!770+1336/100,!0/100", /* 5 */
1547                         "!770+1477/100,!0/100", /* 6 */
1548                         "!852+1209/100,!0/100", /* 7 */
1549                         "!852+1336/100,!0/100", /* 8 */
1550                         "!852+1477/100,!0/100", /* 9 */
1551                         "!697+1633/100,!0/100", /* A */
1552                         "!770+1633/100,!0/100", /* B */
1553                         "!852+1633/100,!0/100", /* C */
1554                         "!941+1633/100,!0/100", /* D */
1555                         "!941+1209/100,!0/100", /* * */
1556                         "!941+1477/100,!0/100" };       /* # */
1557                 if (digit >= '0' && digit <='9')
1558                         ast_playtones_start(chan,0,dtmf_tones[digit-'0'], 0);
1559                 else if (digit >= 'A' && digit <= 'D')
1560                         ast_playtones_start(chan,0,dtmf_tones[digit-'A'+10], 0);
1561                 else if (digit == '*')
1562                         ast_playtones_start(chan,0,dtmf_tones[14], 0);
1563                 else if (digit == '#')
1564                         ast_playtones_start(chan,0,dtmf_tones[15], 0);
1565                 else {
1566                         /* not handled */
1567                         ast_log(LOG_DEBUG, "Unable to handle DTMF tone '%c' for '%s'\n", digit, chan->name);
1568                 }
1569         }
1570         return 0;
1571 }
1572
1573 int ast_senddigit(struct ast_channel *chan, char digit)
1574 {
1575         return do_senddigit(chan, digit);
1576 }
1577
1578 int ast_prod(struct ast_channel *chan)
1579 {
1580         struct ast_frame a = { AST_FRAME_VOICE };
1581         char nothing[128];
1582         /* Send an empty audio frame to get things moving */
1583         if (chan->_state != AST_STATE_UP) {
1584                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1585                 a.subclass = chan->rawwriteformat;
1586                 a.data = nothing + AST_FRIENDLY_OFFSET;
1587                 a.src = "ast_prod";
1588                 if (ast_write(chan, &a))
1589                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1590         }
1591         return 0;
1592 }
1593
1594 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1595 {
1596         int res;
1597         if (!chan->tech->write_video)
1598                 return 0;
1599         res = ast_write(chan, fr);
1600         if (!res)
1601                 res = 1;
1602         return res;
1603 }
1604
1605 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1606 {
1607         int res = -1;
1608         struct ast_frame *f = NULL;
1609         /* Stop if we're a zombie or need a soft hangup */
1610         ast_mutex_lock(&chan->lock);
1611         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1612                 ast_mutex_unlock(&chan->lock);
1613                 return -1;
1614         }
1615         /* Handle any pending masquerades */
1616         if (chan->masq) {
1617                 if (ast_do_masquerade(chan)) {
1618                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1619                         ast_mutex_unlock(&chan->lock);
1620                         return -1;
1621                 }
1622         }
1623         if (chan->masqr) {
1624                 ast_mutex_unlock(&chan->lock);
1625                 return 0;
1626         }
1627         if (chan->generatordata) {
1628                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1629                         ast_deactivate_generator(chan);
1630                 else {
1631                         ast_mutex_unlock(&chan->lock);
1632                         return 0;
1633                 }
1634         }
1635         if (chan->fout & 0x80000000)
1636                 ast_frame_dump(chan->name, fr, ">>");
1637         CHECK_BLOCKING(chan);
1638         switch(fr->frametype) {
1639         case AST_FRAME_CONTROL:
1640                 /* XXX Interpret control frames XXX */
1641                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1642                 break;
1643         case AST_FRAME_DTMF:
1644                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1645                 ast_mutex_unlock(&chan->lock);
1646                 res = do_senddigit(chan,fr->subclass);
1647                 ast_mutex_lock(&chan->lock);
1648                 CHECK_BLOCKING(chan);
1649                 break;
1650         case AST_FRAME_TEXT:
1651                 if (chan->tech->send_text)
1652                         res = chan->tech->send_text(chan, (char *) fr->data);
1653                 else
1654                         res = 0;
1655                 break;
1656         case AST_FRAME_HTML:
1657                 if (chan->tech->send_html)
1658                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1659                 else
1660                         res = 0;
1661                 break;
1662         case AST_FRAME_VIDEO:
1663                 /* XXX Handle translation of video codecs one day XXX */
1664                 if (chan->tech->write_video)
1665                         res = chan->tech->write_video(chan, fr);
1666                 else
1667                         res = 0;
1668                 break;
1669         default:
1670                 if (chan->tech->write) {
1671                         if (chan->writetrans) {
1672                                 f = ast_translate(chan->writetrans, fr, 0);
1673                         } else
1674                                 f = fr;
1675                         if (f) {
1676                                 res = chan->tech->write(chan, f);
1677                                 if( chan->monitor &&
1678                                                 chan->monitor->write_stream &&
1679                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
1680 #ifndef MONITOR_CONSTANT_DELAY
1681                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
1682                                         if (jump >= 0) {
1683                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1684                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1685                                                 chan->outsmpl += jump + 2 * f->samples;
1686                                         } else
1687                                                 chan->outsmpl += f->samples;
1688 #else
1689                                         int jump = chan->insmpl - chan->outsmpl;
1690                                         if (jump - MONITOR_DELAY >= 0) {
1691                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1692                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
1693                                                 chan->outsmpl += jump;
1694                                         } else
1695                                                 chan->outsmpl += f->samples;
1696 #endif
1697                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
1698                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
1699                                 }
1700                         } else
1701                                 res = 0;
1702                 }
1703         }
1704         if (f && (f != fr))
1705                 ast_frfree(f);
1706         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1707         /* Consider a write failure to force a soft hangup */
1708         if (res < 0)
1709                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1710         else {
1711                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
1712                         chan->fout &= 0x80000000;
1713                 else
1714                         chan->fout++;
1715                 chan->fout++;
1716         }
1717         ast_mutex_unlock(&chan->lock);
1718         return res;
1719 }
1720
1721 int ast_set_write_format(struct ast_channel *chan, int fmts)
1722 {
1723         int fmt;
1724         int native;
1725         int res;
1726         
1727         ast_mutex_lock(&chan->lock);
1728         native = chan->nativeformats;
1729         fmt = fmts;
1730         
1731         res = ast_translator_best_choice(&native, &fmt);
1732         if (res < 0) {
1733                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1734                         ast_getformatname(fmts), ast_getformatname(chan->nativeformats));
1735                 ast_mutex_unlock(&chan->lock);
1736                 return -1;
1737         }
1738         
1739         /* Now we have a good choice for both.  We'll write using our native format. */
1740         chan->rawwriteformat = native;
1741         /* User perspective is fmt */
1742         chan->writeformat = fmt;
1743         /* Free any write translation we have right now */
1744         if (chan->writetrans)
1745                 ast_translator_free_path(chan->writetrans);
1746         /* Build a translation path from the user write format to the raw writing format */
1747         chan->writetrans = ast_translator_build_path(chan->rawwriteformat, chan->writeformat);
1748         if (option_debug)
1749                 ast_log(LOG_DEBUG, "Set channel %s to write format %s\n", chan->name, ast_getformatname(chan->writeformat));
1750         ast_mutex_unlock(&chan->lock);
1751         return 0;
1752 }
1753
1754 int ast_set_read_format(struct ast_channel *chan, int fmts)
1755 {
1756         int fmt;
1757         int native;
1758         int res;
1759         
1760         ast_mutex_lock(&chan->lock);
1761         native = chan->nativeformats;
1762         fmt = fmts;
1763         /* Find a translation path from the native read format to one of the user's read formats */
1764         res = ast_translator_best_choice(&fmt, &native);
1765         if (res < 0) {
1766                 ast_log(LOG_NOTICE, "Unable to find a path from %s to %s\n",
1767                         ast_getformatname(chan->nativeformats), ast_getformatname(fmts));
1768                 ast_mutex_unlock(&chan->lock);
1769                 return -1;
1770         }
1771         
1772         /* Now we have a good choice for both.  We'll write using our native format. */
1773         chan->rawreadformat = native;
1774         /* User perspective is fmt */
1775         chan->readformat = fmt;
1776         /* Free any read translation we have right now */
1777         if (chan->readtrans)
1778                 ast_translator_free_path(chan->readtrans);
1779         /* Build a translation path from the raw read format to the user reading format */
1780         chan->readtrans = ast_translator_build_path(chan->readformat, chan->rawreadformat);
1781         if (option_debug)
1782                 ast_log(LOG_DEBUG, "Set channel %s to read format %s\n", 
1783                         chan->name, ast_getformatname(chan->readformat));
1784         ast_mutex_unlock(&chan->lock);
1785         return 0;
1786 }
1787
1788 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)
1789 {
1790         int state = 0;
1791         int cause = 0;
1792         struct ast_channel *chan;
1793         struct ast_frame *f;
1794         int res = 0;
1795         char *variable;
1796         chan = ast_request(type, format, data, &cause);
1797         if (chan) {
1798                 if (oh) {
1799                         char *tmp, *var;
1800                         /* JDG chanvar */
1801                         if (oh->variable)
1802                                 variable = ast_strdupa(oh->variable);
1803                         else
1804                                 variable = NULL;
1805                         tmp = variable;
1806                         /* FIXME replace this call with strsep  NOT*/
1807                         while( (var = strtok_r(NULL, "|", &tmp)) ) {
1808                                 pbx_builtin_setvar( chan, var );
1809                         } /* /JDG */
1810                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
1811                         if (oh->account && *oh->account)
1812                                 ast_cdr_setaccount(chan, oh->account);
1813                 }
1814                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
1815
1816                 if (!ast_call(chan, data, 0)) {
1817                         while(timeout && (chan->_state != AST_STATE_UP)) {
1818                                 res = ast_waitfor(chan, timeout);
1819                                 if (res < 0) {
1820                                         /* Something not cool, or timed out */
1821                                         break;
1822                                 }
1823                                 /* If done, break out */
1824                                 if (!res)
1825                                         break;
1826                                 if (timeout > -1)
1827                                         timeout = res;
1828                                 f = ast_read(chan);
1829                                 if (!f) {
1830                                         state = AST_CONTROL_HANGUP;
1831                                         res = 0;
1832                                         break;
1833                                 }
1834                                 if (f->frametype == AST_FRAME_CONTROL) {
1835                                         if (f->subclass == AST_CONTROL_RINGING)
1836                                                 state = AST_CONTROL_RINGING;
1837                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
1838                                                 state = f->subclass;
1839                                                 ast_frfree(f);
1840                                                 break;
1841                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
1842                                                 state = f->subclass;
1843                                                 ast_frfree(f);
1844                                                 break;
1845                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
1846                                                 /* Ignore */
1847                                         } else if (f->subclass == -1) {
1848                                                 /* Ignore -- just stopping indications */
1849                                         } else {
1850                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
1851                                         }
1852                                 }
1853                                 ast_frfree(f);
1854                         }
1855                 } else
1856                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
1857         } else {
1858                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
1859                 switch(cause) {
1860                 case AST_CAUSE_BUSY:
1861                         state = AST_CONTROL_BUSY;
1862                         break;
1863                 case AST_CAUSE_CONGESTION:
1864                         state = AST_CONTROL_CONGESTION;
1865                         break;
1866                 }
1867         }
1868         if (chan) {
1869                 /* Final fixups */
1870                 if (oh) {
1871                         if (oh->context && *oh->context)
1872                                 strncpy(chan->context, oh->context, sizeof(chan->context) - 1);
1873                         if (oh->exten && *oh->exten)
1874                                 strncpy(chan->exten, oh->exten, sizeof(chan->exten) - 1);
1875                         chan->priority = oh->priority;
1876                 }
1877                 if (chan->_state == AST_STATE_UP) 
1878                         state = AST_CONTROL_ANSWER;
1879         }
1880         if (outstate)
1881                 *outstate = state;
1882         if (chan && res <= 0) {
1883                 if (!chan->cdr) {
1884                         chan->cdr = ast_cdr_alloc();
1885                         if (chan->cdr)
1886                                 ast_cdr_init(chan->cdr, chan);
1887                 }
1888                 if (chan->cdr) {
1889                         char tmp[256];
1890                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
1891                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
1892                         ast_cdr_update(chan);
1893                         ast_cdr_start(chan->cdr);
1894                         ast_cdr_end(chan->cdr);
1895                         /* If the cause wasn't handled properly */
1896                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
1897                                 ast_cdr_failed(chan->cdr);
1898                 } else 
1899                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
1900                 ast_hangup(chan);
1901                 chan = NULL;
1902         }
1903         return chan;
1904 }
1905
1906 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
1907 {
1908         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
1909 }
1910
1911 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
1912 {
1913         struct chanlist *chan;
1914         struct ast_channel *c = NULL;
1915         int capabilities;
1916         int fmt;
1917         int res;
1918         int foo;
1919         if (!cause)
1920                 cause = &foo;
1921         *cause = AST_CAUSE_NOTDEFINED;
1922         if (ast_mutex_lock(&chlock)) {
1923                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
1924                 return NULL;
1925         }
1926         chan = backends;
1927         while(chan) {
1928                 if (!strcasecmp(type, chan->tech->type)) {
1929                         capabilities = chan->tech->capabilities;
1930                         fmt = format;
1931                         res = ast_translator_best_choice(&fmt, &capabilities);
1932                         if (res < 0) {
1933                                 ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
1934                                 ast_mutex_unlock(&chlock);
1935                                 return NULL;
1936                         }
1937                         ast_mutex_unlock(&chlock);
1938                         if (chan->tech->requester)
1939                                 c = chan->tech->requester(type, capabilities, data, cause);
1940                         if (c) {
1941                                 if (c->_state == AST_STATE_DOWN) {
1942                                         manager_event(EVENT_FLAG_CALL, "Newchannel",
1943                                         "Channel: %s\r\n"
1944                                         "State: %s\r\n"
1945                                         "CallerID: %s\r\n"
1946                                         "CallerIDName: %s\r\n"
1947                                         "Uniqueid: %s\r\n",
1948                                         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);
1949                                 }
1950                         }
1951                         return c;
1952                 }
1953                 chan = chan->next;
1954         }
1955         if (!chan) {
1956                 ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
1957                 *cause = AST_CAUSE_NOSUCHDRIVER;
1958         }
1959         ast_mutex_unlock(&chlock);
1960         return c;
1961 }
1962
1963 int ast_parse_device_state(char *device)
1964 {
1965         char name[AST_CHANNEL_NAME] = "";
1966         char *cut;
1967         struct ast_channel *chan;
1968
1969         chan = ast_channel_walk_locked(NULL);
1970         while (chan) {
1971                 strncpy(name, chan->name, sizeof(name)-1);
1972                 ast_mutex_unlock(&chan->lock);
1973                 cut = strchr(name,'-');
1974                 if (cut)
1975                         *cut = 0;
1976                 if (!strcmp(name, device))
1977                         return AST_DEVICE_INUSE;
1978                 chan = ast_channel_walk_locked(chan);
1979         }
1980         return AST_DEVICE_UNKNOWN;
1981 }
1982
1983 int ast_device_state(char *device)
1984 {
1985         char tech[AST_MAX_EXTENSION] = "";
1986         char *number;
1987         struct chanlist *chanls;
1988         int res = 0;
1989         
1990         strncpy(tech, device, sizeof(tech)-1);
1991         number = strchr(tech, '/');
1992         if (!number) {
1993             return AST_DEVICE_INVALID;
1994         }
1995         *number = 0;
1996         number++;
1997                 
1998         if (ast_mutex_lock(&chlock)) {
1999                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2000                 return -1;
2001         }
2002         chanls = backends;
2003         while(chanls) {
2004                 if (!strcasecmp(tech, chanls->tech->type)) {
2005                         ast_mutex_unlock(&chlock);
2006                         if (!chanls->tech->devicestate) 
2007                                 return ast_parse_device_state(device);
2008                         else {
2009                                 res = chanls->tech->devicestate(number);
2010                                 if (res == AST_DEVICE_UNKNOWN)
2011                                         return ast_parse_device_state(device);
2012                                 else
2013                                         return res;
2014                         }
2015                 }
2016                 chanls = chanls->next;
2017         }
2018         ast_mutex_unlock(&chlock);
2019         return AST_DEVICE_INVALID;
2020 }
2021
2022 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2023 {
2024         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2025            If the remote end does not answer within the timeout, then do NOT hang up, but 
2026            return anyway.  */
2027         int res = -1;
2028         /* Stop if we're a zombie or need a soft hangup */
2029         ast_mutex_lock(&chan->lock);
2030         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2031                 if (chan->tech->call)
2032                         res = chan->tech->call(chan, addr, timeout);
2033         ast_mutex_unlock(&chan->lock);
2034         return res;
2035 }
2036
2037 int ast_transfer(struct ast_channel *chan, char *dest) 
2038 {
2039         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2040            If the remote end does not answer within the timeout, then do NOT hang up, but 
2041            return anyway.  */
2042         int res = -1;
2043         /* Stop if we're a zombie or need a soft hangup */
2044         ast_mutex_lock(&chan->lock);
2045         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2046                 if (chan->tech->transfer) {
2047                         res = chan->tech->transfer(chan, dest);
2048                         if (!res)
2049                                 res = 1;
2050                 } else
2051                         res = 0;
2052         }
2053         ast_mutex_unlock(&chan->lock);
2054         return res;
2055 }
2056
2057 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2058 {
2059         int pos=0;
2060         int to = ftimeout;
2061         char d;
2062         /* XXX Merge with full version? XXX */
2063         /* Stop if we're a zombie or need a soft hangup */
2064         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2065                 return -1;
2066         if (!len)
2067                 return -1;
2068         do {
2069                 if (c->stream) {
2070                         d = ast_waitstream(c, AST_DIGIT_ANY);
2071                         ast_stopstream(c);
2072                         usleep(1000);
2073                         if (!d)
2074                                 d = ast_waitfordigit(c, to);
2075                 } else {
2076                         d = ast_waitfordigit(c, to);
2077                 }
2078                 if (d < 0)
2079                         return -1;
2080                 if (d == 0) {
2081                         s[pos]='\0';
2082                         return 1;
2083                 }
2084                 if (!strchr(enders, d))
2085                         s[pos++] = d;
2086                 if (strchr(enders, d) || (pos >= len)) {
2087                         s[pos]='\0';
2088                         return 0;
2089                 }
2090                 to = timeout;
2091         } while(1);
2092         /* Never reached */
2093         return 0;
2094 }
2095
2096 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2097 {
2098         int pos=0;
2099         int to = ftimeout;
2100         char d;
2101         /* Stop if we're a zombie or need a soft hangup */
2102         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2103                 return -1;
2104         if (!len)
2105                 return -1;
2106         do {
2107                 if (c->stream) {
2108                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2109                         ast_stopstream(c);
2110                         usleep(1000);
2111                         if (!d)
2112                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2113                 } else {
2114                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2115                 }
2116                 if (d < 0)
2117                         return -1;
2118                 if (d == 0) {
2119                         s[pos]='\0';
2120                         return 1;
2121                 }
2122                 if (d == 1) {
2123                         s[pos]='\0';
2124                         return 2;
2125                 }
2126                 if (!strchr(enders, d))
2127                         s[pos++] = d;
2128                 if (strchr(enders, d) || (pos >= len)) {
2129                         s[pos]='\0';
2130                         return 0;
2131                 }
2132                 to = timeout;
2133         } while(1);
2134         /* Never reached */
2135         return 0;
2136 }
2137
2138 int ast_channel_supports_html(struct ast_channel *chan)
2139 {
2140         if (chan->tech->send_html)
2141                 return 1;
2142         return 0;
2143 }
2144
2145 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, char *data, int datalen)
2146 {
2147         if (chan->tech->send_html)
2148                 return chan->tech->send_html(chan, subclass, data, datalen);
2149         return -1;
2150 }
2151
2152 int ast_channel_sendurl(struct ast_channel *chan, char *url)
2153 {
2154         if (chan->tech->send_html)
2155                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2156         return -1;
2157 }
2158
2159 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2160 {
2161         int peerf;
2162         int chanf;
2163         int res;
2164         ast_mutex_lock(&peer->lock);
2165         peerf = peer->nativeformats;
2166         ast_mutex_unlock(&peer->lock);
2167         ast_mutex_lock(&chan->lock);
2168         chanf = chan->nativeformats;
2169         ast_mutex_unlock(&chan->lock);
2170         res = ast_translator_best_choice(&peerf, &chanf);
2171         if (res < 0) {
2172                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, chan->nativeformats, peer->name, peer->nativeformats);
2173                 return -1;
2174         }
2175         /* Set read format on channel */
2176         res = ast_set_read_format(chan, peerf);
2177         if (res < 0) {
2178                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, chanf);
2179                 return -1;
2180         }
2181         /* Set write format on peer channel */
2182         res = ast_set_write_format(peer, peerf);
2183         if (res < 0) {
2184                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, peerf);
2185                 return -1;
2186         }
2187         /* Now we go the other way */
2188         peerf = peer->nativeformats;
2189         chanf = chan->nativeformats;
2190         res = ast_translator_best_choice(&chanf, &peerf);
2191         if (res < 0) {
2192                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, peer->nativeformats, chan->name, chan->nativeformats);
2193                 return -1;
2194         }
2195         /* Set writeformat on channel */
2196         res = ast_set_write_format(chan, chanf);
2197         if (res < 0) {
2198                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, chanf);
2199                 return -1;
2200         }
2201         /* Set read format on peer channel */
2202         res = ast_set_read_format(peer, chanf);
2203         if (res < 0) {
2204                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, peerf);
2205                 return -1;
2206         }
2207         return 0;
2208 }
2209
2210 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2211 {
2212         struct ast_frame null = { AST_FRAME_NULL, };
2213         int res = -1;
2214         if (original == clone) {
2215                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2216                 return -1;
2217         }
2218         ast_mutex_lock(&original->lock);
2219         while(ast_mutex_trylock(&clone->lock)) {
2220                 ast_mutex_unlock(&original->lock);
2221                 usleep(1);
2222                 ast_mutex_lock(&original->lock);
2223         }
2224         ast_log(LOG_DEBUG, "Planning to masquerade %s into the structure of %s\n",
2225                 clone->name, original->name);
2226         if (original->masq) {
2227                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2228                         original->masq->name, original->name);
2229         } else if (clone->masqr) {
2230                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2231                         clone->name, clone->masqr->name);
2232         } else {
2233                 original->masq = clone;
2234                 clone->masqr = original;
2235                 ast_queue_frame(original, &null);
2236                 ast_queue_frame(clone, &null);
2237                 ast_log(LOG_DEBUG, "Done planning to masquerade %s into the structure of %s\n", original->name, clone->name);
2238                 res = 0;
2239         }
2240         ast_mutex_unlock(&clone->lock);
2241         ast_mutex_unlock(&original->lock);
2242         return res;
2243 }
2244
2245 void ast_change_name(struct ast_channel *chan, char *newname)
2246 {
2247         char tmp[256];
2248         strncpy(tmp, chan->name, sizeof(tmp) - 1);
2249         strncpy(chan->name, newname, sizeof(chan->name) - 1);
2250         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2251 }
2252
2253 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2254 {
2255         struct ast_var_t *current, *newvar;
2256         char *varname;
2257
2258         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2259                 int vartype = 0;
2260
2261                 varname = ast_var_full_name(current);
2262                 if (!varname)
2263                         continue;
2264
2265                 if (varname[0] == '_') {
2266                         vartype = 1;
2267                         if (varname[1] == '_')
2268                                 vartype = 2;
2269                 }
2270
2271                 switch (vartype) {
2272                 case 1:
2273                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2274                         if (newvar) {
2275                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2276                                 if (option_debug)
2277                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2278                         }
2279                         break;
2280                 case 2:
2281                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2282                         if (newvar) {
2283                                 AST_LIST_INSERT_HEAD(&child->varshead, newvar, entries);
2284                                 if (option_debug)
2285                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2286                         }
2287                         break;
2288                 default:
2289                         if (option_debug)
2290                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2291                         break;
2292                 }
2293         }
2294 }
2295
2296 /* Clone channel variables from 'clone' channel into 'original' channel
2297    All variables except those related to app_groupcount are cloned
2298    Variables are actually _removed_ from 'clone' channel, presumably
2299    because it will subsequently be destroyed.
2300    Assumes locks will be in place on both channels when called.
2301 */
2302    
2303 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2304 {
2305         struct ast_var_t *varptr;
2306
2307         /* we need to remove all app_groupcount related variables from the original
2308            channel before merging in the clone's variables; any groups assigned to the
2309            original channel should be released, only those assigned to the clone
2310            should remain
2311         */
2312
2313         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2314                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2315                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2316                         ast_var_delete(varptr);
2317                 }
2318         }
2319         AST_LIST_TRAVERSE_SAFE_END;
2320
2321         /* Append variables from clone channel into original channel */
2322         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2323         if (AST_LIST_FIRST(&clone->varshead))
2324                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2325 }
2326
2327 /* Assumes channel will be locked when called */
2328 int ast_do_masquerade(struct ast_channel *original)
2329 {
2330         int x,i;
2331         int res=0;
2332         int origstate;
2333         struct ast_frame *cur, *prev;
2334         const struct ast_channel_tech *t;
2335         void *t_pvt;
2336         struct ast_callerid tmpcid;
2337         struct ast_channel *clone = original->masq;
2338         int rformat = original->readformat;
2339         int wformat = original->writeformat;
2340         char newn[100];
2341         char orig[100];
2342         char masqn[100];
2343         char zombn[100];
2344
2345 #if 1
2346         ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2347                 clone->name, clone->_state, original->name, original->_state);
2348 #endif
2349         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2350            the clone channel into the original channel.  Start by killing off the original
2351            channel's backend.   I'm not sure we're going to keep this function, because 
2352            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2353
2354         /* We need the clone's lock, too */
2355         ast_mutex_lock(&clone->lock);
2356
2357         ast_log(LOG_DEBUG, "Got clone lock on '%s' at %p\n", clone->name, &clone->lock);
2358
2359         /* Having remembered the original read/write formats, we turn off any translation on either
2360            one */
2361         free_translation(clone);
2362         free_translation(original);
2363
2364
2365         /* Unlink the masquerade */
2366         original->masq = NULL;
2367         clone->masqr = NULL;
2368         
2369         /* Save the original name */
2370         strncpy(orig, original->name, sizeof(orig) - 1);
2371         /* Save the new name */
2372         strncpy(newn, clone->name, sizeof(newn) - 1);
2373         /* Create the masq name */
2374         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2375                 
2376         /* Copy the name from the clone channel */
2377         strncpy(original->name, newn, sizeof(original->name)-1);
2378
2379         /* Mangle the name of the clone channel */
2380         strncpy(clone->name, masqn, sizeof(clone->name) - 1);
2381         
2382         /* Notify any managers of the change, first the masq then the other */
2383         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2384         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2385
2386         /* Swap the technlogies */      
2387         t = original->tech;
2388         original->tech = clone->tech;
2389         clone->tech = t;
2390
2391         t_pvt = original->tech_pvt;
2392         original->tech_pvt = clone->tech_pvt;
2393         clone->tech_pvt = t_pvt;
2394
2395         /* Swap the readq's */
2396         cur = original->readq;
2397         original->readq = clone->readq;
2398         clone->readq = cur;
2399
2400         /* Swap the alertpipes */
2401         for (i = 0; i < 2; i++) {
2402                 x = original->alertpipe[i];
2403                 original->alertpipe[i] = clone->alertpipe[i];
2404                 clone->alertpipe[i] = x;
2405         }
2406
2407         /* Swap the raw formats */
2408         x = original->rawreadformat;
2409         original->rawreadformat = clone->rawreadformat;
2410         clone->rawreadformat = x;
2411         x = original->rawwriteformat;
2412         original->rawwriteformat = clone->rawwriteformat;
2413         clone->rawwriteformat = x;
2414
2415         /* Save any pending frames on both sides.  Start by counting
2416          * how many we're going to need... */
2417         prev = NULL;
2418         cur = clone->readq;
2419         x = 0;
2420         while(cur) {
2421                 x++;
2422                 prev = cur;
2423                 cur = cur->next;
2424         }
2425         /* If we had any, prepend them to the ones already in the queue, and 
2426          * load up the alertpipe */
2427         if (prev) {
2428                 prev->next = original->readq;
2429                 original->readq = clone->readq;
2430                 clone->readq = NULL;
2431                 if (original->alertpipe[1] > -1) {
2432                         for (i=0;i<x;i++)
2433                                 write(original->alertpipe[1], &x, sizeof(x));
2434                 }
2435         }
2436         clone->_softhangup = AST_SOFTHANGUP_DEV;
2437
2438
2439         /* And of course, so does our current state.  Note we need not
2440            call ast_setstate since the event manager doesn't really consider
2441            these separate.  We do this early so that the clone has the proper
2442            state of the original channel. */
2443         origstate = original->_state;
2444         original->_state = clone->_state;
2445         clone->_state = origstate;
2446
2447         if (clone->tech->fixup){
2448                 res = clone->tech->fixup(original, clone);
2449                 if (res) 
2450                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2451         }
2452
2453         /* Start by disconnecting the original's physical side */
2454         if (clone->tech->hangup)
2455                 res = clone->tech->hangup(clone);
2456         if (res) {
2457                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2458                 ast_mutex_unlock(&clone->lock);
2459                 return -1;
2460         }
2461         
2462         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2463         /* Mangle the name of the clone channel */
2464         strncpy(clone->name, zombn, sizeof(clone->name) - 1);
2465         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2466
2467         /* Update the type. */
2468         original->type = clone->type;
2469         
2470         /* Keep the same language.  */
2471         strncpy(original->language, clone->language, sizeof(original->language));
2472         /* Copy the FD's */
2473         for (x=0;x<AST_MAX_FDS;x++) {
2474                 original->fds[x] = clone->fds[x];
2475         }
2476         clone_variables(original, clone);
2477         clone->varshead.first = NULL;
2478         /* Presense of ADSI capable CPE follows clone */
2479         original->adsicpe = clone->adsicpe;
2480         /* Bridge remains the same */
2481         /* CDR fields remain the same */
2482         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2483         /* Application and data remain the same */
2484         /* Clone exception  becomes real one, as with fdno */
2485         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2486         original->fdno = clone->fdno;
2487         /* Schedule context remains the same */
2488         /* Stream stuff stays the same */
2489         /* Keep the original state.  The fixup code will need to work with it most likely */
2490
2491         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2492            out. */
2493         tmpcid = original->cid;
2494         original->cid = clone->cid;
2495         clone->cid = tmpcid;
2496         
2497         /* Restore original timing file descriptor */
2498         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2499         
2500         /* Our native formats are different now */
2501         original->nativeformats = clone->nativeformats;
2502         
2503         /* Context, extension, priority, app data, jump table,  remain the same */
2504         /* pvt switches.  pbx stays the same, as does next */
2505         
2506         /* Set the write format */
2507         ast_set_write_format(original, wformat);
2508
2509         /* Set the read format */
2510         ast_set_read_format(original, rformat);
2511
2512         /* Copy the music class */
2513         strncpy(original->musicclass, clone->musicclass, sizeof(original->musicclass) - 1);
2514
2515         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2516
2517         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2518            can fix up everything as best as possible */
2519         if (original->tech->fixup) {
2520                 res = original->tech->fixup(clone, original);
2521                 if (res) {
2522                         ast_log(LOG_WARNING, "Driver for '%s' could not fixup channel %s\n",
2523                                 original->type, original->name);
2524                         ast_mutex_unlock(&clone->lock);
2525                         return -1;
2526                 }
2527         } else
2528                 ast_log(LOG_WARNING, "Driver '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2529                         original->type, original->name);
2530         
2531         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2532            a zombie so nothing tries to touch it.  If it's already been marked as a
2533            zombie, then free it now (since it already is considered invalid). */
2534         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2535                 ast_log(LOG_DEBUG, "Destroying clone '%s'\n", clone->name);
2536                 ast_mutex_unlock(&clone->lock);
2537                 ast_channel_free(clone);
2538                 manager_event(EVENT_FLAG_CALL, "Hangup", "Channel: %s\r\n", zombn);
2539         } else {
2540                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2541                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2542                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2543                 ast_queue_frame(clone, &null_frame);
2544                 ast_mutex_unlock(&clone->lock);
2545         }
2546         
2547         /* Signal any blocker */
2548         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2549                 pthread_kill(original->blocker, SIGURG);
2550         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n",
2551                 original->name, original->_state);
2552         return 0;
2553 }
2554
2555 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2556 {
2557         if (callerid) {
2558                 if (chan->cid.cid_num)
2559                         free(chan->cid.cid_num);
2560                 if (ast_strlen_zero(callerid))
2561                         chan->cid.cid_num = NULL;
2562                 else
2563                         chan->cid.cid_num = strdup(callerid);
2564         }
2565         if (calleridname) {
2566                 if (chan->cid.cid_name)
2567                         free(chan->cid.cid_name);
2568                 if (ast_strlen_zero(calleridname))
2569                         chan->cid.cid_name = NULL;
2570                 else
2571                         chan->cid.cid_name = strdup(calleridname);
2572         }
2573         if (ani) {
2574                 if (chan->cid.cid_ani)
2575                         free(chan->cid.cid_ani);
2576                 if (ast_strlen_zero(ani))
2577                         chan->cid.cid_ani = NULL;
2578                 else
2579                         chan->cid.cid_ani = strdup(ani);
2580         }
2581         if (chan->cdr)
2582                 ast_cdr_setcid(chan->cdr, chan);
2583         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2584                                 "Channel: %s\r\n"
2585                                 "CallerID: %s\r\n"
2586                                 "CallerIDName: %s\r\n"
2587                                 "Uniqueid: %s\r\n",
2588                                 chan->name, chan->cid.cid_num ? 
2589                                 chan->cid.cid_num : "<Unknown>",
2590                                 chan->cid.cid_name ? 
2591                                 chan->cid.cid_name : "<Unknown>",
2592                                 chan->uniqueid);
2593 }
2594
2595 int ast_setstate(struct ast_channel *chan, int state)
2596 {
2597         if (chan->_state != state) {
2598                 int oldstate = chan->_state;
2599                 chan->_state = state;
2600                 if (oldstate == AST_STATE_DOWN) {
2601                         ast_device_state_changed(chan->name);
2602                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2603                         "Channel: %s\r\n"
2604                         "State: %s\r\n"
2605                         "CallerID: %s\r\n"
2606                         "CallerIDName: %s\r\n"
2607                         "Uniqueid: %s\r\n",
2608                         chan->name, ast_state2str(chan->_state), 
2609                         chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2610                         chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2611                         chan->uniqueid);
2612                 } else {
2613                         manager_event(EVENT_FLAG_CALL, "Newstate", 
2614                                 "Channel: %s\r\n"
2615                                 "State: %s\r\n"
2616                                 "CallerID: %s\r\n"
2617                                 "CallerIDName: %s\r\n"
2618                                 "Uniqueid: %s\r\n",
2619                                 chan->name, ast_state2str(chan->_state), 
2620                                 chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2621                                 chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2622                                 chan->uniqueid);
2623                 }
2624         }
2625         return 0;
2626 }
2627
2628 static long tvdiff(struct timeval *now, struct timeval *then) 
2629 {
2630 #if 0
2631         return (((now->tv_sec * 1000) + now->tv_usec / 1000) - ((then->tv_sec * 1000) + then->tv_usec / 1000));
2632 #else
2633         return (now->tv_sec - then->tv_sec) * 1000 + (now->tv_usec - then->tv_usec) / 1000;     
2634 #endif
2635 }
2636
2637 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2638 {
2639         struct ast_channel *bridged;
2640         bridged = chan->_bridge;
2641         if (bridged && bridged->tech->bridged_channel) 
2642                 bridged = bridged->tech->bridged_channel(chan, bridged);
2643         return bridged;
2644 }
2645
2646 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2647 {
2648         int res=0, min=0, sec=0,check=0;
2649
2650         check = ast_autoservice_start(peer);
2651         if(check) 
2652                 return;
2653
2654         if (remain > 0) {
2655                 if (remain / 60 > 1) {
2656                         min = remain / 60;
2657                         sec = remain % 60;
2658                 } else {
2659                         sec = remain;
2660                 }
2661         }
2662         
2663         if (!strcmp(sound,"timeleft")) {
2664                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2665                 res = ast_waitstream(chan, "");
2666                 if (min) {
2667                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2668                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2669                         res = ast_waitstream(chan, "");
2670                 }
2671                 if (sec) {
2672                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2673                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2674                         res = ast_waitstream(chan, "");
2675                 }
2676         } else {
2677                 res = ast_streamfile(chan, sound, chan->language);
2678                 res = ast_waitstream(chan, "");
2679         }
2680
2681         check = ast_autoservice_stop(peer);
2682 }
2683
2684 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) 
2685 {
2686         /* Copy voice back and forth between the two channels.  Give the peer
2687            the ability to transfer calls with '#<extension' syntax. */
2688         struct ast_channel *cs[3];
2689         int to = -1;
2690         struct ast_frame *f;
2691         struct ast_channel *who = NULL;
2692         int res=0;
2693         int nativefailed=0;
2694         int firstpass;
2695         int o0nativeformats;
2696         int o1nativeformats;
2697         struct timeval start_time,precise_now;
2698         long elapsed_ms=0, time_left_ms=0;
2699         int playit=0, playitagain=1, first_time=1;
2700
2701         *fo = NULL;
2702         firstpass = config->firstpass;
2703         config->firstpass = 0;
2704
2705         /* timestamp */
2706         gettimeofday(&start_time,NULL);
2707         time_left_ms = config->timelimit;
2708
2709         if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2710                 bridge_playfile(c0,c1,config->start_sound,time_left_ms / 1000);
2711         if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->start_sound && firstpass)
2712                 bridge_playfile(c1,c0,config->start_sound,time_left_ms / 1000);
2713
2714         /* Stop if we're a zombie or need a soft hangup */
2715         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)) 
2716                 return -1;
2717         if (c0->_bridge) {
2718                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2719                         c0->name, c0->_bridge->name);
2720                 return -1;
2721         }
2722         if (c1->_bridge) {
2723                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
2724                         c1->name, c1->_bridge->name);
2725                 return -1;
2726         }
2727         
2728         /* Keep track of bridge */
2729         c0->_bridge = c1;
2730         c1->_bridge = c0;
2731         cs[0] = c0;
2732         cs[1] = c1;
2733         
2734         manager_event(EVENT_FLAG_CALL, "Link", 
2735                         "Channel1: %s\r\n"
2736                         "Channel2: %s\r\n"
2737                         "Uniqueid1: %s\r\n"
2738                         "Uniqueid2: %s\r\n",
2739                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2740         o1nativeformats = c1->nativeformats;
2741         o0nativeformats = c0->nativeformats;
2742         for (/* ever */;;) {
2743                 /* timestamp */
2744                 if (config->timelimit) {
2745                         gettimeofday(&precise_now,NULL);
2746                         elapsed_ms = tvdiff(&precise_now,&start_time);
2747                         time_left_ms = config->timelimit - elapsed_ms;
2748
2749                         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)) { 
2750                                 /* narrowing down to the end */
2751                                 if (config->warning_freq == 0) {
2752                                         playit = 1;
2753                                         first_time=0;
2754                                         playitagain=0;
2755                                 } else if (first_time) {
2756                                         playit = 1;
2757                                         first_time=0;
2758                                 } else {
2759                                         if ((time_left_ms % config->warning_freq) <= 50) {
2760                                                 playit = 1;
2761                                         }
2762                                 }
2763                         }
2764                         if (time_left_ms <= 0) {
2765                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2766                                         bridge_playfile(c0,c1,config->end_sound,0);
2767                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->end_sound)
2768                                         bridge_playfile(c1,c0,config->end_sound,0);
2769                                 *fo = NULL;
2770                                 if (who) *rc = who;
2771                                 res = 0;
2772                                 break;
2773                         }
2774                         if (time_left_ms >= 5000 && playit) {
2775                                 if ((ast_test_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2776                                         bridge_playfile(c0,c1,config->warning_sound,time_left_ms / 1000);
2777                                 if ((ast_test_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING)) && config->warning_sound && config->play_warning)
2778                                         bridge_playfile(c1,c0,config->warning_sound,time_left_ms / 1000);
2779                                 playit = 0;
2780                         }
2781                         
2782                 }
2783                 /* Stop if we're a zombie or need a soft hangup */
2784                 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)) {
2785                         *fo = NULL;
2786                         if (who) *rc = who;
2787                         res = 0;
2788                         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");
2789                         break;
2790                 }
2791                 if (c0->tech->bridge && config->timelimit==0 &&
2792                         (c0->tech->bridge == c1->tech->bridge) && !nativefailed && !c0->monitor && !c1->monitor) {
2793                                 /* Looks like they share a bridge code */
2794                         if (option_verbose > 2) 
2795                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
2796                         if (!(res = c0->tech->bridge(c0, c1, config->flags, fo, rc))) {
2797                                 c0->_bridge = NULL;
2798                                 c1->_bridge = NULL;
2799                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2800                                         "Channel1: %s\r\n"
2801                                         "Channel2: %s\r\n"
2802                                         "Uniqueid1: %s\r\n"
2803                                         "Uniqueid2: %s\r\n",
2804                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2805                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n",c0->name ,c1->name);
2806                                 return 0;
2807                         }
2808                         /* If they return non-zero then continue on normally.  Let "-2" mean don't worry about
2809                            my not wanting to bridge */
2810                         if ((res != -2) && (res != -3))
2811                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
2812                         if (res != -3) nativefailed++;
2813                 }
2814         
2815                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) || (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
2816                         !(c0->generator || c1->generator))  {
2817                         if (ast_channel_make_compatible(c0, c1)) {
2818                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
2819                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
2820                                         "Channel1: %s\r\n"
2821                                         "Channel2: %s\r\n"
2822                                         "Uniqueid1: %s\r\n"
2823                                         "Uniqueid2: %s\r\n",
2824                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2825                                 return -1;
2826                         }
2827                         o0nativeformats = c0->nativeformats;
2828                         o1nativeformats = c1->nativeformats;
2829                 }
2830                 who = ast_waitfor_n(cs, 2, &to);
2831                 if (!who) {
2832                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2833                         continue;
2834                 }
2835                 f = ast_read(who);
2836                 if (!f) {
2837                         *fo = NULL;
2838                         *rc = who;
2839                         res = 0;
2840                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
2841                         break;
2842                 }
2843
2844                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
2845                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD)) {
2846                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
2847                         } else {
2848                                 *fo = f;
2849                                 *rc = who;
2850                                 res =  0;
2851                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
2852                                 break;
2853                         }
2854                 }
2855                 if ((f->frametype == AST_FRAME_VOICE) ||
2856                         (f->frametype == AST_FRAME_TEXT) ||
2857                         (f->frametype == AST_FRAME_VIDEO) || 
2858                         (f->frametype == AST_FRAME_IMAGE) ||
2859                         (f->frametype == AST_FRAME_HTML) ||
2860                         (f->frametype == AST_FRAME_DTMF)) {
2861                         if ((f->frametype == AST_FRAME_DTMF) && 
2862                                 (config->flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
2863                                 if ((who == c0)) {
2864                                         if  ((config->flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
2865                                                 *rc = c0;
2866                                                 *fo = f;
2867                                                 /* Take out of conference mode */
2868                                                 res = 0;
2869                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_0 on c0 (%s)\n",c0->name);
2870                                                 break;
2871                                         } else 
2872                                                 goto tackygoto;
2873                                 } else
2874                                 if ((who == c1)) {
2875                                         if (config->flags & AST_BRIDGE_DTMF_CHANNEL_1) {
2876                                                 *rc = c1;
2877                                                 *fo = f;
2878                                                 res =  0;
2879                                                 ast_log(LOG_DEBUG, "Got AST_BRIDGE_DTMF_CHANNEL_1 on c1 (%s)\n",c1->name);
2880                                                 break;
2881                                         } else
2882                                                 goto tackygoto;
2883                                 }
2884                         } else {
2885 #if 0
2886                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
2887                                 if (who == last) 
2888                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
2889                                 last = who;
2890 #endif
2891 tackygoto:
2892                                 /* Don't copy packets if there is a generator on either one, since they're
2893                                    not supposed to be listening anyway */
2894                                 if (who == c0) 
2895                                         ast_write(c1, f);
2896                                 else 
2897                                         ast_write(c0, f);
2898                         }
2899                 }
2900                 ast_frfree(f);
2901
2902                 /* Swap who gets priority */
2903                 cs[2] = cs[0];
2904                 cs[0] = cs[1];
2905                 cs[1] = cs[2];
2906         }
2907         c0->_bridge = NULL;
2908         c1->_bridge = NULL;
2909         manager_event(EVENT_FLAG_CALL, "Unlink", 
2910                                         "Channel1: %s\r\n"
2911                                         "Channel2: %s\r\n"
2912                                         "Uniqueid1: %s\r\n"
2913                                         "Uniqueid2: %s\r\n",
2914                                         c0->name, c1->name, c0->uniqueid, c1->uniqueid);
2915         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n",c0->name,c1->name);
2916         return res;
2917 }
2918
2919 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
2920 {
2921         int res;
2922         if (chan->tech->setoption) {
2923                 res = chan->tech->setoption(chan, option, data, datalen);
2924                 if (res < 0)
2925                         return res;
2926         } else {
2927                 errno = ENOSYS;
2928                 return -1;
2929         }
2930         if (block) {
2931                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
2932                    intermediate packets. XXX */
2933                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
2934                 return -1;
2935         }
2936         return 0;
2937 }
2938
2939 struct tonepair_def {
2940         int freq1;
2941         int freq2;
2942         int duration;
2943         int vol;
2944 };
2945
2946 struct tonepair_state {
2947         float freq1;
2948         float freq2;
2949         float vol;
2950         int duration;
2951         int pos;
2952         int origwfmt;
2953         struct ast_frame f;
2954         unsigned char offset[AST_FRIENDLY_OFFSET];
2955         short data[4000];
2956 };
2957
2958 static void tonepair_release(struct ast_channel *chan, void *params)
2959 {
2960         struct tonepair_state *ts = params;
2961         if (chan) {
2962                 ast_set_write_format(chan, ts->origwfmt);
2963         }
2964         free(ts);
2965 }
2966
2967 static void * tonepair_alloc(struct ast_channel *chan, void *params)
2968 {
2969         struct tonepair_state *ts;
2970         struct tonepair_def *td = params;
2971         ts = malloc(sizeof(struct tonepair_state));
2972         if (!ts)
2973                 return NULL;
2974         memset(ts, 0, sizeof(struct tonepair_state));
2975         ts->origwfmt = chan->writeformat;
2976         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
2977                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
2978                 tonepair_release(NULL, ts);
2979                 ts = NULL;
2980         } else {
2981                 ts->freq1 = td->freq1;
2982                 ts->freq2 = td->freq2;
2983                 ts->duration = td->duration;
2984                 ts->vol = td->vol;
2985         }
2986         /* Let interrupts interrupt :) */
2987         ast_set_flag(chan, AST_FLAG_WRITE_INT);
2988         return ts;
2989 }
2990
2991 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
2992 {
2993         struct tonepair_state *ts = data;
2994         int x;
2995
2996         /* we need to prepare a frame with 16 * timelen samples as we're 
2997          * generating SLIN audio
2998          */
2999         len = samples * 2;
3000
3001         if (len > sizeof(ts->data) / 2 - 1) {
3002                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
3003                 return -1;
3004         }
3005         memset(&ts->f, 0, sizeof(ts->f));
3006         for (x=0;x<len/2;x++) {
3007                 ts->data[x] = ts->vol * (
3008                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
3009                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
3010                         );
3011         }
3012         ts->f.frametype = AST_FRAME_VOICE;
3013         ts->f.subclass = AST_FORMAT_SLINEAR;
3014         ts->f.datalen = len;
3015         ts->f.samples = samples;
3016         ts->f.offset = AST_FRIENDLY_OFFSET;
3017         ts->f.data = ts->data;
3018         ast_write(chan, &ts->f);
3019         ts->pos += x;
3020         if (ts->duration > 0) {
3021                 if (ts->pos >= ts->duration * 8)
3022                         return -1;
3023         }
3024         return 0;
3025 }
3026
3027 static struct ast_generator tonepair = {
3028         alloc: tonepair_alloc,
3029         release: tonepair_release,
3030         generate: tonepair_generator,
3031 };
3032
3033 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3034 {
3035         struct tonepair_def d = { 0, };
3036         d.freq1 = freq1;
3037         d.freq2 = freq2;
3038         d.duration = duration;
3039         if (vol < 1)
3040                 d.vol = 8192;
3041         else
3042                 d.vol = vol;
3043         if (ast_activate_generator(chan, &tonepair, &d))
3044                 return -1;
3045         return 0;
3046 }
3047
3048 void ast_tonepair_stop(struct ast_channel *chan)
3049 {
3050         ast_deactivate_generator(chan);
3051 }
3052
3053 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3054 {
3055         struct ast_frame *f;
3056         int res;
3057         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3058                 return res;
3059
3060         /* Give us some wiggle room */
3061         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
3062                 f = ast_read(chan);
3063                 if (f)
3064                         ast_frfree(f);
3065                 else
3066                         return -1;
3067         }
3068         return 0;
3069 }
3070
3071 ast_group_t ast_get_group(char *s)
3072 {
3073         char *copy;
3074         char *piece;
3075         char *c=NULL;
3076         int start=0, finish=0,x;
3077         ast_group_t group = 0;
3078         copy = ast_strdupa(s);
3079         if (!copy) {
3080                 ast_log(LOG_ERROR, "Out of memory\n");
3081                 return 0;
3082         }
3083         c = copy;
3084         
3085         while((piece = strsep(&c, ","))) {
3086                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3087                         /* Range */
3088                 } else if (sscanf(piece, "%d", &start)) {
3089                         /* Just one */
3090                         finish = start;
3091                 } else {
3092                         ast_log(LOG_ERROR, "Syntax error parsing '%s' at '%s'.\n", s, piece);
3093                         continue;
3094                 }
3095                 for (x=start;x<=finish;x++) {
3096                         if ((x > 63) || (x < 0)) {
3097                                 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
3098                         } else
3099                                 group |= (1 << x);
3100                 }
3101         }
3102         return group;
3103 }
3104
3105 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
3106 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3107 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3108
3109
3110 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
3111                                                                  void (*stop_ptr)(struct ast_channel *),
3112                                                                  void (*cleanup_ptr)(struct ast_channel *)