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