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