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