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