cf972e952867e10f1198449279a9bb89dffffd5c
[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 /*
20  *
21  * 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_get_channel_by_exten_locked: Get channel by exten (and optionally context) and lock it */
793 struct ast_channel *ast_get_channel_by_exten_locked(const char *exten, const char *context)
794 {
795         return channel_find_locked(NULL, NULL, 0, context, exten);
796 }
797
798 /*--- ast_safe_sleep_conditional: Wait, look for hangups and condition arg */
799 int ast_safe_sleep_conditional( struct ast_channel *chan, int ms,
800         int (*cond)(void*), void *data )
801 {
802         struct ast_frame *f;
803
804         while(ms > 0) {
805                 if( cond && ((*cond)(data) == 0 ) )
806                         return 0;
807                 ms = ast_waitfor(chan, ms);
808                 if (ms <0)
809                         return -1;
810                 if (ms > 0) {
811                         f = ast_read(chan);
812                         if (!f)
813                                 return -1;
814                         ast_frfree(f);
815                 }
816         }
817         return 0;
818 }
819
820 /*--- ast_safe_sleep: Wait, look for hangups */
821 int ast_safe_sleep(struct ast_channel *chan, int ms)
822 {
823         struct ast_frame *f;
824         while(ms > 0) {
825                 ms = ast_waitfor(chan, ms);
826                 if (ms <0)
827                         return -1;
828                 if (ms > 0) {
829                         f = ast_read(chan);
830                         if (!f)
831                                 return -1;
832                         ast_frfree(f);
833                 }
834         }
835         return 0;
836 }
837
838 static void free_cid(struct ast_callerid *cid)
839 {
840         if (cid->cid_dnid)
841                 free(cid->cid_dnid);
842         if (cid->cid_num)
843                 free(cid->cid_num);     
844         if (cid->cid_name)
845                 free(cid->cid_name);    
846         if (cid->cid_ani)
847                 free(cid->cid_ani);
848         if (cid->cid_rdnis)
849                 free(cid->cid_rdnis);
850 }
851
852 /*--- ast_channel_free: Free a channel structure */
853 void ast_channel_free(struct ast_channel *chan)
854 {
855         struct ast_channel *last=NULL, *cur;
856         int fd;
857         struct ast_var_t *vardata;
858         struct ast_frame *f, *fp;
859         struct varshead *headp;
860         char name[AST_CHANNEL_NAME];
861         
862         headp=&chan->varshead;
863         
864         ast_mutex_lock(&chlock);
865         cur = channels;
866         while(cur) {
867                 if (cur == chan) {
868                         if (last)
869                                 last->next = cur->next;
870                         else
871                                 channels = cur->next;
872                         break;
873                 }
874                 last = cur;
875                 cur = cur->next;
876         }
877         if (!cur)
878                 ast_log(LOG_WARNING, "Unable to find channel in list\n");
879         else {
880                 /* Lock and unlock the channel just to be sure nobody
881                    has it locked still */
882                 ast_mutex_lock(&cur->lock);
883                 ast_mutex_unlock(&cur->lock);
884         }
885         if (chan->tech_pvt) {
886                 ast_log(LOG_WARNING, "Channel '%s' may not have been hung up properly\n", chan->name);
887                 free(chan->tech_pvt);
888         }
889
890         ast_copy_string(name, chan->name, sizeof(name));
891         
892         /* Stop monitoring */
893         if (chan->monitor) {
894                 chan->monitor->stop( chan, 0 );
895         }
896
897         /* If there is native format music-on-hold state, free it */
898         if(chan->music_state)
899                 ast_moh_cleanup(chan);
900
901         /* Free translatosr */
902         if (chan->readtrans)
903                 ast_translator_free_path(chan->readtrans);
904         if (chan->writetrans)
905                 ast_translator_free_path(chan->writetrans);
906         if (chan->pbx) 
907                 ast_log(LOG_WARNING, "PBX may not have been terminated properly on '%s'\n", chan->name);
908         free_cid(&chan->cid);
909         ast_mutex_destroy(&chan->lock);
910         /* Close pipes if appropriate */
911         if ((fd = chan->alertpipe[0]) > -1)
912                 close(fd);
913         if ((fd = chan->alertpipe[1]) > -1)
914                 close(fd);
915         if ((fd = chan->timingfd) > -1)
916                 close(fd);
917         f = chan->readq;
918         chan->readq = NULL;
919         while(f) {
920                 fp = f;
921                 f = f->next;
922                 ast_frfree(fp);
923         }
924         
925         /* loop over the variables list, freeing all data and deleting list items */
926         /* no need to lock the list, as the channel is already locked */
927         
928         while (!AST_LIST_EMPTY(headp)) {           /* List Deletion. */
929                     vardata = AST_LIST_REMOVE_HEAD(headp, entries);
930                     ast_var_delete(vardata);
931         }
932
933         free(chan);
934         ast_mutex_unlock(&chlock);
935
936         ast_device_state_changed(name);
937 }
938
939 static void ast_spy_detach(struct ast_channel *chan) 
940 {
941         struct ast_channel_spy *chanspy;
942         int to=3000;
943         int sleepms = 100;
944
945         for (chanspy = chan->spiers; chanspy; chanspy = chanspy->next) {
946                 if (chanspy->status == CHANSPY_RUNNING) {
947                         chanspy->status = CHANSPY_DONE;
948                 }
949         }
950
951         /* signal all the spys to get lost and allow them time to unhook themselves 
952            god help us if they don't......
953         */
954         while (chan->spiers && to >= 0) {
955                 ast_safe_sleep(chan, sleepms);
956                 to -= sleepms;
957         }
958         chan->spiers = NULL;
959         return;
960 }
961
962 /*--- ast_softhangup_nolock: Softly hangup a channel, don't lock */
963 int ast_softhangup_nolock(struct ast_channel *chan, int cause)
964 {
965         int res = 0;
966         struct ast_frame f = { AST_FRAME_NULL };
967         if (option_debug)
968                 ast_log(LOG_DEBUG, "Soft-Hanging up channel '%s'\n", chan->name);
969         /* Inform channel driver that we need to be hung up, if it cares */
970         chan->_softhangup |= cause;
971         ast_queue_frame(chan, &f);
972         /* Interrupt any poll call or such */
973         if (ast_test_flag(chan, AST_FLAG_BLOCKING))
974                 pthread_kill(chan->blocker, SIGURG);
975         return res;
976 }
977
978 /*--- ast_softhangup_nolock: Softly hangup a channel, lock */
979 int ast_softhangup(struct ast_channel *chan, int cause)
980 {
981         int res;
982         ast_mutex_lock(&chan->lock);
983         res = ast_softhangup_nolock(chan, cause);
984         ast_mutex_unlock(&chan->lock);
985         return res;
986 }
987
988 static void ast_queue_spy_frame(struct ast_channel_spy *spy, struct ast_frame *f, int pos) 
989 {
990         struct ast_frame *tmpf = NULL;
991         int count = 0;
992
993         ast_mutex_lock(&spy->lock);
994         for (tmpf=spy->queue[pos]; tmpf && tmpf->next; tmpf=tmpf->next) {
995                 count++;
996         }
997         if (count > 1000) {
998                 struct ast_frame *freef, *headf;
999
1000                 ast_log(LOG_ERROR, "Too many frames queued at once, flushing cache.\n");
1001                 headf = spy->queue[pos];
1002                 /* deref the queue right away so it looks empty */
1003                 spy->queue[pos] = NULL;
1004                 tmpf = headf;
1005                 /* free the wasted frames */
1006                 while (tmpf) {
1007                         freef = tmpf;
1008                         tmpf = tmpf->next;
1009                         ast_frfree(freef);
1010                 }
1011                 ast_mutex_unlock(&spy->lock);
1012                 return;
1013         }
1014
1015         if (tmpf) {
1016                 tmpf->next = ast_frdup(f);
1017         } else {
1018                 spy->queue[pos] = ast_frdup(f);
1019         }
1020
1021         ast_mutex_unlock(&spy->lock);
1022 }
1023
1024 static void free_translation(struct ast_channel *clone)
1025 {
1026         if (clone->writetrans)
1027                 ast_translator_free_path(clone->writetrans);
1028         if (clone->readtrans)
1029                 ast_translator_free_path(clone->readtrans);
1030         clone->writetrans = NULL;
1031         clone->readtrans = NULL;
1032         clone->rawwriteformat = clone->nativeformats;
1033         clone->rawreadformat = clone->nativeformats;
1034 }
1035
1036 /*--- ast_hangup: Hangup a channel */
1037 int ast_hangup(struct ast_channel *chan)
1038 {
1039         int res = 0;
1040
1041         /* Don't actually hang up a channel that will masquerade as someone else, or
1042            if someone is going to masquerade as us */
1043         ast_mutex_lock(&chan->lock);
1044
1045         ast_spy_detach(chan);           /* get rid of spies */
1046
1047         if (chan->masq) {
1048                 if (ast_do_masquerade(chan)) 
1049                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1050         }
1051
1052         if (chan->masq) {
1053                 ast_log(LOG_WARNING, "%s getting hung up, but someone is trying to masq into us?!?\n", chan->name);
1054                 ast_mutex_unlock(&chan->lock);
1055                 return 0;
1056         }
1057         /* If this channel is one which will be masqueraded into something, 
1058            mark it as a zombie already, so we know to free it later */
1059         if (chan->masqr) {
1060                 ast_set_flag(chan, AST_FLAG_ZOMBIE);
1061                 ast_mutex_unlock(&chan->lock);
1062                 return 0;
1063         }
1064         free_translation(chan);
1065         if (chan->stream)               /* Close audio stream */
1066                 ast_closestream(chan->stream);
1067         if (chan->vstream)              /* Close video stream */
1068                 ast_closestream(chan->vstream);
1069         if (chan->sched)
1070                 sched_context_destroy(chan->sched);
1071         
1072         if (chan->generatordata)        /* Clear any tone stuff remaining */ 
1073                 chan->generator->release(chan, chan->generatordata);
1074         chan->generatordata = NULL;
1075         chan->generator = NULL;
1076         if (chan->cdr) {                /* End the CDR if it hasn't already */ 
1077                 ast_cdr_end(chan->cdr);
1078                 ast_cdr_detach(chan->cdr);      /* Post and Free the CDR */ 
1079                 chan->cdr = NULL;
1080         }
1081         if (ast_test_flag(chan, AST_FLAG_BLOCKING)) {
1082                 ast_log(LOG_WARNING, "Hard hangup called by thread %ld on %s, while fd "
1083                                         "is blocked by thread %ld in procedure %s!  Expect a failure\n",
1084                                         (long)pthread_self(), chan->name, (long)chan->blocker, chan->blockproc);
1085                 CRASH;
1086         }
1087         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE)) {
1088                 if (option_debug)
1089                         ast_log(LOG_DEBUG, "Hanging up channel '%s'\n", chan->name);
1090                 if (chan->tech->hangup)
1091                         res = chan->tech->hangup(chan);
1092         } else {
1093                 if (option_debug)
1094                         ast_log(LOG_DEBUG, "Hanging up zombie '%s'\n", chan->name);
1095         }
1096                         
1097         ast_mutex_unlock(&chan->lock);
1098         manager_event(EVENT_FLAG_CALL, "Hangup", 
1099                         "Channel: %s\r\n"
1100                         "Uniqueid: %s\r\n"
1101                         "Cause: %d\r\n"
1102                         "Cause-txt: %s\r\n",
1103                         chan->name, 
1104                         chan->uniqueid, 
1105                         chan->hangupcause,
1106                         ast_cause2str(chan->hangupcause)
1107                         );
1108         ast_channel_free(chan);
1109         return res;
1110 }
1111
1112 int ast_answer(struct ast_channel *chan)
1113 {
1114         int res = 0;
1115         ast_mutex_lock(&chan->lock);
1116         /* Stop if we're a zombie or need a soft hangup */
1117         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1118                 ast_mutex_unlock(&chan->lock);
1119                 return -1;
1120         }
1121         switch(chan->_state) {
1122         case AST_STATE_RINGING:
1123         case AST_STATE_RING:
1124                 if (chan->tech->answer)
1125                         res = chan->tech->answer(chan);
1126                 ast_setstate(chan, AST_STATE_UP);
1127                 if (chan->cdr)
1128                         ast_cdr_answer(chan->cdr);
1129                 ast_mutex_unlock(&chan->lock);
1130                 return res;
1131                 break;
1132         case AST_STATE_UP:
1133                 if (chan->cdr)
1134                         ast_cdr_answer(chan->cdr);
1135                 break;
1136         }
1137         ast_mutex_unlock(&chan->lock);
1138         return 0;
1139 }
1140
1141
1142
1143 void ast_deactivate_generator(struct ast_channel *chan)
1144 {
1145         ast_mutex_lock(&chan->lock);
1146         if (chan->generatordata) {
1147                 if (chan->generator && chan->generator->release) 
1148                         chan->generator->release(chan, chan->generatordata);
1149                 chan->generatordata = NULL;
1150                 chan->generator = NULL;
1151                 ast_clear_flag(chan, AST_FLAG_WRITE_INT);
1152                 ast_settimeout(chan, 0, NULL, NULL);
1153         }
1154         ast_mutex_unlock(&chan->lock);
1155 }
1156
1157 static int generator_force(void *data)
1158 {
1159         /* Called if generator doesn't have data */
1160         void *tmp;
1161         int res;
1162         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1163         struct ast_channel *chan = data;
1164         tmp = chan->generatordata;
1165         chan->generatordata = NULL;
1166         generate = chan->generator->generate;
1167         res = generate(chan, tmp, 0, 160);
1168         chan->generatordata = tmp;
1169         if (res) {
1170                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1171                 ast_deactivate_generator(chan);
1172         }
1173         return 0;
1174 }
1175
1176 int ast_activate_generator(struct ast_channel *chan, struct ast_generator *gen, void *params)
1177 {
1178         int res = 0;
1179         ast_mutex_lock(&chan->lock);
1180         if (chan->generatordata) {
1181                 if (chan->generator && chan->generator->release)
1182                         chan->generator->release(chan, chan->generatordata);
1183                 chan->generatordata = NULL;
1184         }
1185         ast_prod(chan);
1186         if ((chan->generatordata = gen->alloc(chan, params))) {
1187                 ast_settimeout(chan, 160, generator_force, chan);
1188                 chan->generator = gen;
1189         } else {
1190                 res = -1;
1191         }
1192         ast_mutex_unlock(&chan->lock);
1193         return res;
1194 }
1195
1196 /*--- ast_waitfor_n_fd: Wait for x amount of time on a file descriptor to have input.  */
1197 int ast_waitfor_n_fd(int *fds, int n, int *ms, int *exception)
1198 {
1199         struct timeval start = { 0 , 0 };
1200         int res;
1201         int x, y;
1202         int winner = -1;
1203         int spoint;
1204         struct pollfd *pfds;
1205         
1206         pfds = alloca(sizeof(struct pollfd) * n);
1207         if (!pfds) {
1208                 ast_log(LOG_ERROR, "Out of memory\n");
1209                 return -1;
1210         }
1211         if (*ms > 0)
1212                 start = ast_tvnow();
1213         y = 0;
1214         for (x=0; x < n; x++) {
1215                 if (fds[x] > -1) {
1216                         pfds[y].fd = fds[x];
1217                         pfds[y].events = POLLIN | POLLPRI;
1218                         y++;
1219                 }
1220         }
1221         res = poll(pfds, y, *ms);
1222         if (res < 0) {
1223                 /* Simulate a timeout if we were interrupted */
1224                 if (errno != EINTR)
1225                         *ms = -1;
1226                 else
1227                         *ms = 0;
1228                 return -1;
1229         }
1230         spoint = 0;
1231         for (x=0; x < n; x++) {
1232                 if (fds[x] > -1) {
1233                         if ((res = ast_fdisset(pfds, fds[x], y, &spoint))) {
1234                                 winner = fds[x];
1235                                 if (exception) {
1236                                         if (res & POLLPRI)
1237                                                 *exception = -1;
1238                                         else
1239                                                 *exception = 0;
1240                                 }
1241                         }
1242                 }
1243         }
1244         if (*ms > 0) {
1245                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1246                 if (*ms < 0)
1247                         *ms = 0;
1248         }
1249         return winner;
1250 }
1251
1252 /*--- ast_waitfor_nanfds: Wait for x amount of time on a file descriptor to have input.  */
1253 struct ast_channel *ast_waitfor_nandfds(struct ast_channel **c, int n, int *fds, int nfds, 
1254         int *exception, int *outfd, int *ms)
1255 {
1256         struct timeval start = { 0 , 0 };
1257         struct pollfd *pfds;
1258         int res;
1259         long rms;
1260         int x, y, max;
1261         int spoint;
1262         time_t now = 0;
1263         long whentohangup = 0, havewhen = 0, diff;
1264         struct ast_channel *winner = NULL;
1265
1266         pfds = alloca(sizeof(struct pollfd) * (n * AST_MAX_FDS + nfds));
1267         if (!pfds) {
1268                 ast_log(LOG_ERROR, "Out of memory\n");
1269                 *outfd = -1;
1270                 return NULL;
1271         }
1272
1273         if (outfd)
1274                 *outfd = -99999;
1275         if (exception)
1276                 *exception = 0;
1277         
1278         /* Perform any pending masquerades */
1279         for (x=0; x < n; x++) {
1280                 ast_mutex_lock(&c[x]->lock);
1281                 if (c[x]->whentohangup) {
1282                         if (!havewhen)
1283                                 time(&now);
1284                         diff = c[x]->whentohangup - now;
1285                         if (!havewhen || (diff < whentohangup)) {
1286                                 havewhen++;
1287                                 whentohangup = diff;
1288                         }
1289                 }
1290                 if (c[x]->masq) {
1291                         if (ast_do_masquerade(c[x])) {
1292                                 ast_log(LOG_WARNING, "Masquerade failed\n");
1293                                 *ms = -1;
1294                                 ast_mutex_unlock(&c[x]->lock);
1295                                 return NULL;
1296                         }
1297                 }
1298                 ast_mutex_unlock(&c[x]->lock);
1299         }
1300
1301         rms = *ms;
1302         
1303         if (havewhen) {
1304                 if ((*ms < 0) || (whentohangup * 1000 < *ms)) {
1305                         rms =  whentohangup * 1000;
1306                 }
1307         }
1308         max = 0;
1309         for (x=0; x < n; x++) {
1310                 for (y=0; y< AST_MAX_FDS; y++) {
1311                         if (c[x]->fds[y] > -1) {
1312                                 pfds[max].fd = c[x]->fds[y];
1313                                 pfds[max].events = POLLIN | POLLPRI;
1314                                 pfds[max].revents = 0;
1315                                 max++;
1316                         }
1317                 }
1318                 CHECK_BLOCKING(c[x]);
1319         }
1320         for (x=0; x < nfds; x++) {
1321                 if (fds[x] > -1) {
1322                         pfds[max].fd = fds[x];
1323                         pfds[max].events = POLLIN | POLLPRI;
1324                         pfds[max].revents = 0;
1325                         max++;
1326                 }
1327         }
1328         if (*ms > 0) 
1329                 start = ast_tvnow();
1330         res = poll(pfds, max, rms);
1331         if (res < 0) {
1332                 for (x=0; x < n; x++) 
1333                         ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1334                 /* Simulate a timeout if we were interrupted */
1335                 if (errno != EINTR)
1336                         *ms = -1;
1337                 else {
1338                         /* Just an interrupt */
1339 #if 0
1340                         *ms = 0;
1341 #endif                  
1342                 }
1343                 return NULL;
1344         } else {
1345                 /* If no fds signalled, then timeout. So set ms = 0
1346                    since we may not have an exact timeout.
1347                 */
1348                 if (res == 0)
1349                         *ms = 0;
1350         }
1351
1352         if (havewhen)
1353                 time(&now);
1354         spoint = 0;
1355         for (x=0; x < n; x++) {
1356                 ast_clear_flag(c[x], AST_FLAG_BLOCKING);
1357                 if (havewhen && c[x]->whentohangup && (now > c[x]->whentohangup)) {
1358                         c[x]->_softhangup |= AST_SOFTHANGUP_TIMEOUT;
1359                         if (!winner)
1360                                 winner = c[x];
1361                 }
1362                 for (y=0; y < AST_MAX_FDS; y++) {
1363                         if (c[x]->fds[y] > -1) {
1364                                 if ((res = ast_fdisset(pfds, c[x]->fds[y], max, &spoint))) {
1365                                         if (res & POLLPRI)
1366                                                 ast_set_flag(c[x], AST_FLAG_EXCEPTION);
1367                                         else
1368                                                 ast_clear_flag(c[x], AST_FLAG_EXCEPTION);
1369                                         c[x]->fdno = y;
1370                                         winner = c[x];
1371                                 }
1372                         }
1373                 }
1374         }
1375         for (x=0; x < nfds; x++) {
1376                 if (fds[x] > -1) {
1377                         if ((res = ast_fdisset(pfds, fds[x], max, &spoint))) {
1378                                 if (outfd)
1379                                         *outfd = fds[x];
1380                                 if (exception) {        
1381                                         if (res & POLLPRI) 
1382                                                 *exception = -1;
1383                                         else
1384                                                 *exception = 0;
1385                                 }
1386                                 winner = NULL;
1387                         }
1388                 }       
1389         }
1390         if (*ms > 0) {
1391                 *ms -= ast_tvdiff_ms(ast_tvnow(), start);
1392                 if (*ms < 0)
1393                         *ms = 0;
1394         }
1395         return winner;
1396 }
1397
1398 struct ast_channel *ast_waitfor_n(struct ast_channel **c, int n, int *ms)
1399 {
1400         return ast_waitfor_nandfds(c, n, NULL, 0, NULL, NULL, ms);
1401 }
1402
1403 int ast_waitfor(struct ast_channel *c, int ms)
1404 {
1405         struct ast_channel *chan;
1406         int oldms = ms;
1407
1408         chan = ast_waitfor_n(&c, 1, &ms);
1409         if (ms < 0) {
1410                 if (oldms < 0)
1411                         return 0;
1412                 else
1413                         return -1;
1414         }
1415         return ms;
1416 }
1417
1418 int ast_waitfordigit(struct ast_channel *c, int ms)
1419 {
1420         /* XXX Should I be merged with waitfordigit_full XXX */
1421         struct ast_frame *f;
1422         int result = 0;
1423
1424         /* Stop if we're a zombie or need a soft hangup */
1425         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1426                 return -1;
1427
1428         /* Wait for a digit, no more than ms milliseconds total. */
1429         while(ms && !result) {
1430                 ms = ast_waitfor(c, ms);
1431                 if (ms < 0) /* Error */
1432                         result = -1; 
1433                 else if (ms > 0) {
1434                         /* Read something */
1435                         f = ast_read(c);
1436                         if (f) {
1437                                 if (f->frametype == AST_FRAME_DTMF) 
1438                                         result = f->subclass;
1439                                 ast_frfree(f);
1440                         } else
1441                                 result = -1;
1442                 }
1443         }
1444         return result;
1445 }
1446
1447 int ast_settimeout(struct ast_channel *c, int samples, int (*func)(void *data), void *data)
1448 {
1449         int res = -1;
1450 #ifdef ZAPTEL_OPTIMIZATIONS
1451         if (c->timingfd > -1) {
1452                 if (!func) {
1453                         samples = 0;
1454                         data = 0;
1455                 }
1456                 ast_log(LOG_DEBUG, "Scheduling timer at %d sample intervals\n", samples);
1457                 res = ioctl(c->timingfd, ZT_TIMERCONFIG, &samples);
1458                 c->timingfunc = func;
1459                 c->timingdata = data;
1460         }
1461 #endif  
1462         return res;
1463 }
1464
1465 int ast_waitfordigit_full(struct ast_channel *c, int ms, int audiofd, int cmdfd)
1466 {
1467         struct ast_frame *f;
1468         struct ast_channel *rchan;
1469         int outfd;
1470         int res;
1471
1472         /* Stop if we're a zombie or need a soft hangup */
1473         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
1474                 return -1;
1475         /* Wait for a digit, no more than ms milliseconds total. */
1476         while(ms) {
1477                 errno = 0;
1478                 rchan = ast_waitfor_nandfds(&c, 1, &cmdfd, (cmdfd > -1) ? 1 : 0, NULL, &outfd, &ms);
1479                 if ((!rchan) && (outfd < 0) && (ms)) { 
1480                         if (errno == 0 || errno == EINTR)
1481                                 continue;
1482                         ast_log(LOG_WARNING, "Wait failed (%s)\n", strerror(errno));
1483                         return -1;
1484                 } else if (outfd > -1) {
1485                         /* The FD we were watching has something waiting */
1486                         return 1;
1487                 } else if (rchan) {
1488                         f = ast_read(c);
1489                         if(!f) {
1490                                 return -1;
1491                         }
1492
1493                         switch(f->frametype) {
1494                         case AST_FRAME_DTMF:
1495                                 res = f->subclass;
1496                                 ast_frfree(f);
1497                                 return res;
1498                         case AST_FRAME_CONTROL:
1499                                 switch(f->subclass) {
1500                                 case AST_CONTROL_HANGUP:
1501                                         ast_frfree(f);
1502                                         return -1;
1503                                 case AST_CONTROL_RINGING:
1504                                 case AST_CONTROL_ANSWER:
1505                                         /* Unimportant */
1506                                         break;
1507                                 default:
1508                                         ast_log(LOG_WARNING, "Unexpected control subclass '%d'\n", f->subclass);
1509                                 }
1510                         case AST_FRAME_VOICE:
1511                                 /* Write audio if appropriate */
1512                                 if (audiofd > -1)
1513                                         write(audiofd, f->data, f->datalen);
1514                         }
1515                         /* Ignore */
1516                         ast_frfree(f);
1517                 }
1518         }
1519         return 0; /* Time is up */
1520 }
1521
1522 struct ast_frame *ast_read(struct ast_channel *chan)
1523 {
1524         struct ast_frame *f = NULL;
1525         int blah;
1526         int prestate;
1527 #ifdef ZAPTEL_OPTIMIZATIONS
1528         int (*func)(void *);
1529         void *data;
1530         int res;
1531 #endif
1532         static struct ast_frame null_frame = {
1533                 AST_FRAME_NULL,
1534         };
1535         
1536         ast_mutex_lock(&chan->lock);
1537         if (chan->masq) {
1538                 if (ast_do_masquerade(chan)) {
1539                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1540                         f = NULL;
1541                 } else
1542                         f =  &null_frame;
1543                 ast_mutex_unlock(&chan->lock);
1544                 return f;
1545         }
1546
1547         /* Stop if we're a zombie or need a soft hangup */
1548         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
1549                 if (chan->generator)
1550                         ast_deactivate_generator(chan);
1551                 ast_mutex_unlock(&chan->lock);
1552                 return NULL;
1553         }
1554         prestate = chan->_state;
1555
1556         if (!ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && !ast_strlen_zero(chan->dtmfq)) {
1557                 /* We have DTMF that has been deferred.  Return it now */
1558                 chan->dtmff.frametype = AST_FRAME_DTMF;
1559                 chan->dtmff.subclass = chan->dtmfq[0];
1560                 /* Drop first digit */
1561                 memmove(chan->dtmfq, chan->dtmfq + 1, sizeof(chan->dtmfq) - 1);
1562                 ast_mutex_unlock(&chan->lock);
1563                 return &chan->dtmff;
1564         }
1565         
1566         /* Read and ignore anything on the alertpipe, but read only
1567            one sizeof(blah) per frame that we send from it */
1568         if (chan->alertpipe[0] > -1) {
1569                 read(chan->alertpipe[0], &blah, sizeof(blah));
1570         }
1571 #ifdef ZAPTEL_OPTIMIZATIONS
1572         if ((chan->timingfd > -1) && (chan->fdno == AST_MAX_FDS - 2) && ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1573                 ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1574                 blah = -1;
1575                 /* IF we can't get event, assume it's an expired as-per the old interface */
1576                 res = ioctl(chan->timingfd, ZT_GETEVENT, &blah);
1577                 if (res) 
1578                         blah = ZT_EVENT_TIMER_EXPIRED;
1579
1580                 if (blah == ZT_EVENT_TIMER_PING) {
1581 #if 0
1582                         ast_log(LOG_NOTICE, "Oooh, there's a PING!\n");
1583 #endif                  
1584                         if (!chan->readq || !chan->readq->next) {
1585                                 /* Acknowledge PONG unless we need it again */
1586 #if 0
1587                                 ast_log(LOG_NOTICE, "Sending a PONG!\n");
1588 #endif                          
1589                                 if (ioctl(chan->timingfd, ZT_TIMERPONG, &blah)) {
1590                                         ast_log(LOG_WARNING, "Failed to pong timer on '%s': %s\n", chan->name, strerror(errno));
1591                                 }
1592                         }
1593                 } else if (blah == ZT_EVENT_TIMER_EXPIRED) {
1594                         ioctl(chan->timingfd, ZT_TIMERACK, &blah);
1595                         func = chan->timingfunc;
1596                         data = chan->timingdata;
1597                         ast_mutex_unlock(&chan->lock);
1598                         if (func) {
1599 #if 0
1600                                 ast_log(LOG_DEBUG, "Calling private function\n");
1601 #endif                  
1602                                 func(data);
1603                         } else {
1604                                 blah = 0;
1605                                 ast_mutex_lock(&chan->lock);
1606                                 ioctl(chan->timingfd, ZT_TIMERCONFIG, &blah);
1607                                 chan->timingdata = NULL;
1608                                 ast_mutex_unlock(&chan->lock);
1609                         }
1610                         f =  &null_frame;
1611                         return f;
1612                 } else
1613                         ast_log(LOG_NOTICE, "No/unknown event '%d' on timer for '%s'?\n", blah, chan->name);
1614         }
1615 #endif
1616         /* Check for pending read queue */
1617         if (chan->readq) {
1618                 f = chan->readq;
1619                 chan->readq = f->next;
1620                 /* Interpret hangup and return NULL */
1621                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1622                         ast_frfree(f);
1623                         f = NULL;
1624                 }
1625         } else {
1626                 chan->blocker = pthread_self();
1627                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1628                         if (chan->tech->exception) 
1629                                 f = chan->tech->exception(chan);
1630                         else {
1631                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1632                                 f = &null_frame;
1633                         }
1634                         /* Clear the exception flag */
1635                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1636                 } else {
1637                         if (chan->tech->read)
1638                                 f = chan->tech->read(chan);
1639                         else
1640                                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1641                 }
1642         }
1643
1644
1645         if (f && (f->frametype == AST_FRAME_VOICE)) {
1646                 if (!(f->subclass & chan->nativeformats)) {
1647                         /* This frame can't be from the current native formats -- drop it on the
1648                            floor */
1649                         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));
1650                         ast_frfree(f);
1651                         f = &null_frame;
1652                 } else {
1653                         if (chan->spiers) {
1654                                 struct ast_channel_spy *spying;
1655                                 for (spying = chan->spiers; spying; spying=spying->next) {
1656                                         ast_queue_spy_frame(spying, f, 0);
1657                                 }
1658                         }
1659                         if (chan->monitor && chan->monitor->read_stream ) {
1660 #ifndef MONITOR_CONSTANT_DELAY
1661                                 int jump = chan->outsmpl - chan->insmpl - 2 * f->samples;
1662                                 if (jump >= 0) {
1663                                         if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1664                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1665                                         chan->insmpl += jump + 2 * f->samples;
1666                                 } else
1667                                         chan->insmpl+= f->samples;
1668 #else
1669                                 int jump = chan->outsmpl - chan->insmpl;
1670                                 if (jump - MONITOR_DELAY >= 0) {
1671                                         if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1672                                                 ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1673                                         chan->insmpl += jump;
1674                                 } else
1675                                         chan->insmpl += f->samples;
1676 #endif
1677                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
1678                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
1679                         }
1680                         if (chan->readtrans) {
1681                                 f = ast_translate(chan->readtrans, f, 1);
1682                                 if (!f)
1683                                         f = &null_frame;
1684                         }
1685                 }
1686         }
1687
1688         /* Make sure we always return NULL in the future */
1689         if (!f) {
1690                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
1691                 if (chan->generator)
1692                         ast_deactivate_generator(chan);
1693                 /* End the CDR if appropriate */
1694                 if (chan->cdr)
1695                         ast_cdr_end(chan->cdr);
1696         } else if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF) && f->frametype == AST_FRAME_DTMF) {
1697                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1698                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1699                 else
1700                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1701                 f = &null_frame;
1702         } else if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_ANSWER)) {
1703                 if (prestate == AST_STATE_UP) {
1704                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1705                         f = &null_frame;
1706                 }
1707                 /* Answer the CDR */
1708                 ast_setstate(chan, AST_STATE_UP);
1709                 ast_cdr_answer(chan->cdr);
1710         } 
1711
1712         /* Run any generator sitting on the line */
1713         if (f && (f->frametype == AST_FRAME_VOICE) && chan->generatordata) {
1714                 /* Mask generator data temporarily and apply.  If there is a timing function, it
1715                    will be calling the generator instead */
1716                 void *tmp;
1717                 int res;
1718                 int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
1719
1720                 if (chan->timingfunc) {
1721                         ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
1722                         ast_settimeout(chan, 0, NULL, NULL);
1723                 }
1724                 tmp = chan->generatordata;
1725                 chan->generatordata = NULL;
1726                 generate = chan->generator->generate;
1727                 res = generate(chan, tmp, f->datalen, f->samples);
1728                 chan->generatordata = tmp;
1729                 if (res) {
1730                         ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
1731                         ast_deactivate_generator(chan);
1732                 }
1733         } else if (f && (f->frametype == AST_FRAME_CNG)) {
1734                 if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
1735                         ast_log(LOG_DEBUG, "Generator got CNG, switching to zap timed mode\n");
1736                         ast_settimeout(chan, 160, generator_force, chan);
1737                 }
1738         }
1739         /* High bit prints debugging */
1740         if (chan->fin & 0x80000000)
1741                 ast_frame_dump(chan->name, f, "<<");
1742         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
1743                 chan->fin &= 0x80000000;
1744         else
1745                 chan->fin++;
1746         ast_mutex_unlock(&chan->lock);
1747         return f;
1748 }
1749
1750 int ast_indicate(struct ast_channel *chan, int condition)
1751 {
1752         int res = -1;
1753
1754         /* Stop if we're a zombie or need a soft hangup */
1755         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1756                 return -1;
1757         ast_mutex_lock(&chan->lock);
1758         if (chan->tech->indicate)
1759                 res = chan->tech->indicate(chan, condition);
1760         ast_mutex_unlock(&chan->lock);
1761         if (!chan->tech->indicate || res) {
1762                 /*
1763                  * Device does not support (that) indication, lets fake
1764                  * it by doing our own tone generation. (PM2002)
1765                  */
1766                 if (condition >= 0) {
1767                         const struct tone_zone_sound *ts = NULL;
1768                         switch (condition) {
1769                         case AST_CONTROL_RINGING:
1770                                 ts = ast_get_indication_tone(chan->zone, "ring");
1771                                 break;
1772                         case AST_CONTROL_BUSY:
1773                                 ts = ast_get_indication_tone(chan->zone, "busy");
1774                                 break;
1775                         case AST_CONTROL_CONGESTION:
1776                                 ts = ast_get_indication_tone(chan->zone, "congestion");
1777                                 break;
1778                         }
1779                         if (ts && ts->data[0]) {
1780                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
1781                                 ast_playtones_start(chan,0,ts->data, 1);
1782                                 res = 0;
1783                         } else if (condition == AST_CONTROL_PROGRESS) {
1784                                 /* ast_playtones_stop(chan); */
1785                         } else if (condition == AST_CONTROL_PROCEEDING) {
1786                                 /* Do nothing, really */
1787                         } else if (condition == AST_CONTROL_HOLD) {
1788                                 /* Do nothing.... */
1789                         } else if (condition == AST_CONTROL_UNHOLD) {
1790                                 /* Do nothing.... */
1791                         } else if (condition == AST_CONTROL_VIDUPDATE) {
1792                                 /* Do nothing.... */
1793                         } else {
1794                                 /* not handled */
1795                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
1796                                 res = -1;
1797                         }
1798                 }
1799                 else ast_playtones_stop(chan);
1800         }
1801         return res;
1802 }
1803
1804 int ast_recvchar(struct ast_channel *chan, int timeout)
1805 {
1806         int c;
1807         char *buf = ast_recvtext(chan, timeout);
1808         if (buf == NULL)
1809                 return -1;      /* error or timeout */
1810         c = *(unsigned char *)buf;
1811         free(buf);
1812         return c;
1813 }
1814
1815 char *ast_recvtext(struct ast_channel *chan, int timeout)
1816 {
1817         int res, done = 0;
1818         char *buf = NULL;
1819         
1820         while (!done) {
1821                 struct ast_frame *f;
1822                 if (ast_check_hangup(chan))
1823                         break;
1824                 res = ast_waitfor(chan, timeout);
1825                 if (res <= 0) /* timeout or error */
1826                         break;
1827                 timeout = res;  /* update timeout */
1828                 f = ast_read(chan);
1829                 if (f == NULL)
1830                         break; /* no frame */
1831                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
1832                         done = 1;       /* force a break */
1833                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
1834                         buf = strndup((char *) f->data, f->datalen);    /* dup and break */
1835                         done = 1;
1836                 }
1837                 ast_frfree(f);
1838         }
1839         return buf;
1840 }
1841
1842 int ast_sendtext(struct ast_channel *chan, char *text)
1843 {
1844         int res = 0;
1845         /* Stop if we're a zombie or need a soft hangup */
1846         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
1847                 return -1;
1848         CHECK_BLOCKING(chan);
1849         if (chan->tech->send_text)
1850                 res = chan->tech->send_text(chan, text);
1851         ast_clear_flag(chan, AST_FLAG_BLOCKING);
1852         return res;
1853 }
1854
1855 static int do_senddigit(struct ast_channel *chan, char digit)
1856 {
1857         int res = -1;
1858
1859         if (chan->tech->send_digit)
1860                 res = chan->tech->send_digit(chan, digit);
1861         if (!chan->tech->send_digit || res) {
1862                 /*
1863                  * Device does not support DTMF tones, lets fake
1864                  * it by doing our own generation. (PM2002)
1865                  */
1866                 static const char* dtmf_tones[] = {
1867                         "!941+1336/100,!0/100", /* 0 */
1868                         "!697+1209/100,!0/100", /* 1 */
1869                         "!697+1336/100,!0/100", /* 2 */
1870                         "!697+1477/100,!0/100", /* 3 */
1871                         "!770+1209/100,!0/100", /* 4 */
1872                         "!770+1336/100,!0/100", /* 5 */
1873                         "!770+1477/100,!0/100", /* 6 */
1874                         "!852+1209/100,!0/100", /* 7 */
1875                         "!852+1336/100,!0/100", /* 8 */
1876                         "!852+1477/100,!0/100", /* 9 */
1877                         "!697+1633/100,!0/100", /* A */
1878                         "!770+1633/100,!0/100", /* B */
1879                         "!852+1633/100,!0/100", /* C */
1880                         "!941+1633/100,!0/100", /* D */
1881                         "!941+1209/100,!0/100", /* * */
1882                         "!941+1477/100,!0/100" };       /* # */
1883                 if (digit >= '0' && digit <='9')
1884                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
1885                 else if (digit >= 'A' && digit <= 'D')
1886                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
1887                 else if (digit == '*')
1888                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
1889                 else if (digit == '#')
1890                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
1891                 else {
1892                         /* not handled */
1893                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
1894                 }
1895         }
1896         return 0;
1897 }
1898
1899 int ast_senddigit(struct ast_channel *chan, char digit)
1900 {
1901         return do_senddigit(chan, digit);
1902 }
1903
1904 int ast_prod(struct ast_channel *chan)
1905 {
1906         struct ast_frame a = { AST_FRAME_VOICE };
1907         char nothing[128];
1908
1909         /* Send an empty audio frame to get things moving */
1910         if (chan->_state != AST_STATE_UP) {
1911                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
1912                 a.subclass = chan->rawwriteformat;
1913                 a.data = nothing + AST_FRIENDLY_OFFSET;
1914                 a.src = "ast_prod";
1915                 if (ast_write(chan, &a))
1916                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
1917         }
1918         return 0;
1919 }
1920
1921 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
1922 {
1923         int res;
1924         if (!chan->tech->write_video)
1925                 return 0;
1926         res = ast_write(chan, fr);
1927         if (!res)
1928                 res = 1;
1929         return res;
1930 }
1931
1932 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
1933 {
1934         int res = -1;
1935         struct ast_frame *f = NULL;
1936         /* Stop if we're a zombie or need a soft hangup */
1937         ast_mutex_lock(&chan->lock);
1938         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
1939                 ast_mutex_unlock(&chan->lock);
1940                 return -1;
1941         }
1942         /* Handle any pending masquerades */
1943         if (chan->masq) {
1944                 if (ast_do_masquerade(chan)) {
1945                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
1946                         ast_mutex_unlock(&chan->lock);
1947                         return -1;
1948                 }
1949         }
1950         if (chan->masqr) {
1951                 ast_mutex_unlock(&chan->lock);
1952                 return 0;
1953         }
1954         if (chan->generatordata) {
1955                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
1956                         ast_deactivate_generator(chan);
1957                 else {
1958                         ast_mutex_unlock(&chan->lock);
1959                         return 0;
1960                 }
1961         }
1962         /* High bit prints debugging */
1963         if (chan->fout & 0x80000000)
1964                 ast_frame_dump(chan->name, fr, ">>");
1965         CHECK_BLOCKING(chan);
1966         switch(fr->frametype) {
1967         case AST_FRAME_CONTROL:
1968                 /* XXX Interpret control frames XXX */
1969                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
1970                 break;
1971         case AST_FRAME_DTMF:
1972                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
1973                 ast_mutex_unlock(&chan->lock);
1974                 res = do_senddigit(chan,fr->subclass);
1975                 ast_mutex_lock(&chan->lock);
1976                 CHECK_BLOCKING(chan);
1977                 break;
1978         case AST_FRAME_TEXT:
1979                 if (chan->tech->send_text)
1980                         res = chan->tech->send_text(chan, (char *) fr->data);
1981                 else
1982                         res = 0;
1983                 break;
1984         case AST_FRAME_HTML:
1985                 if (chan->tech->send_html)
1986                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
1987                 else
1988                         res = 0;
1989                 break;
1990         case AST_FRAME_VIDEO:
1991                 /* XXX Handle translation of video codecs one day XXX */
1992                 if (chan->tech->write_video)
1993                         res = chan->tech->write_video(chan, fr);
1994                 else
1995                         res = 0;
1996                 break;
1997         default:
1998                 if (chan->tech->write) {
1999                         if (chan->writetrans) 
2000                                 f = ast_translate(chan->writetrans, fr, 0);
2001                         else
2002                                 f = fr;
2003                         if (f) {
2004                                 if (f->frametype == AST_FRAME_VOICE && chan->spiers) {
2005                                         struct ast_channel_spy *spying;
2006                                         for (spying = chan->spiers; spying; spying=spying->next) {
2007                                                 ast_queue_spy_frame(spying, f, 1);
2008                                         }
2009                                 }
2010
2011                                 if( chan->monitor && chan->monitor->write_stream &&
2012                                                 f && ( f->frametype == AST_FRAME_VOICE ) ) {
2013 #ifndef MONITOR_CONSTANT_DELAY
2014                                         int jump = chan->insmpl - chan->outsmpl - 2 * f->samples;
2015                                         if (jump >= 0) {
2016                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2017                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2018                                                 chan->outsmpl += jump + 2 * f->samples;
2019                                         } else
2020                                                 chan->outsmpl += f->samples;
2021 #else
2022                                         int jump = chan->insmpl - chan->outsmpl;
2023                                         if (jump - MONITOR_DELAY >= 0) {
2024                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2025                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2026                                                 chan->outsmpl += jump;
2027                                         } else
2028                                                 chan->outsmpl += f->samples;
2029 #endif
2030                                         if (ast_writestream(chan->monitor->write_stream, f) < 0)
2031                                                 ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2032                                 }
2033
2034                                 res = chan->tech->write(chan, f);
2035                         } else
2036                                 res = 0;
2037                 }
2038         }
2039
2040         /* It's possible this is a translated frame */
2041         if (f && f->frametype == AST_FRAME_DTMF) {
2042                 ast_log(LOG_DTMF, "%s : %c\n", chan->name, f->subclass);
2043         } else if (fr->frametype == AST_FRAME_DTMF) {
2044                 ast_log(LOG_DTMF, "%s : %c\n", chan->name, fr->subclass);
2045         }
2046
2047         if (f && (f != fr))
2048                 ast_frfree(f);
2049         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2050         /* Consider a write failure to force a soft hangup */
2051         if (res < 0)
2052                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2053         else {
2054                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2055                         chan->fout &= 0x80000000;
2056                 else
2057                         chan->fout++;
2058         }
2059         ast_mutex_unlock(&chan->lock);
2060         return res;
2061 }
2062
2063 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2064                       struct ast_trans_pvt **trans, const int direction)
2065 {
2066         int native;
2067         int res;
2068         
2069         native = chan->nativeformats;
2070         /* Find a translation path from the native format to one of the desired formats */
2071         if (!direction)
2072                 /* reading */
2073                 res = ast_translator_best_choice(&fmt, &native);
2074         else
2075                 /* writing */
2076                 res = ast_translator_best_choice(&native, &fmt);
2077
2078         if (res < 0) {
2079                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2080                         ast_getformatname(native), ast_getformatname(fmt));
2081                 return -1;
2082         }
2083         
2084         /* Now we have a good choice for both. */
2085         ast_mutex_lock(&chan->lock);
2086         *rawformat = native;
2087         /* User perspective is fmt */
2088         *format = fmt;
2089         /* Free any read translation we have right now */
2090         if (*trans)
2091                 ast_translator_free_path(*trans);
2092         /* Build a translation path from the raw format to the desired format */
2093         if (!direction)
2094                 /* reading */
2095                 *trans = ast_translator_build_path(*format, *rawformat);
2096         else
2097                 /* writing */
2098                 *trans = ast_translator_build_path(*rawformat, *format);
2099         ast_mutex_unlock(&chan->lock);
2100         if (option_debug)
2101                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2102                         direction ? "write" : "read", ast_getformatname(fmt));
2103         return 0;
2104 }
2105
2106 int ast_set_read_format(struct ast_channel *chan, int fmt)
2107 {
2108         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2109                           &chan->readtrans, 0);
2110 }
2111
2112 int ast_set_write_format(struct ast_channel *chan, int fmt)
2113 {
2114         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2115                           &chan->writetrans, 1);
2116 }
2117
2118 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)
2119 {
2120         int state = 0;
2121         int cause = 0;
2122         struct ast_channel *chan;
2123         struct ast_frame *f;
2124         int res = 0;
2125         
2126         chan = ast_request(type, format, data, &cause);
2127         if (chan) {
2128                 if (oh) {
2129                         ast_set_variables(chan, oh->vars);
2130                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2131                 }
2132                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2133
2134                 if (!ast_call(chan, data, 0)) {
2135                         while(timeout && (chan->_state != AST_STATE_UP)) {
2136                                 res = ast_waitfor(chan, timeout);
2137                                 if (res < 0) {
2138                                         /* Something not cool, or timed out */
2139                                         break;
2140                                 }
2141                                 /* If done, break out */
2142                                 if (!res)
2143                                         break;
2144                                 if (timeout > -1)
2145                                         timeout = res;
2146                                 f = ast_read(chan);
2147                                 if (!f) {
2148                                         state = AST_CONTROL_HANGUP;
2149                                         res = 0;
2150                                         break;
2151                                 }
2152                                 if (f->frametype == AST_FRAME_CONTROL) {
2153                                         if (f->subclass == AST_CONTROL_RINGING)
2154                                                 state = AST_CONTROL_RINGING;
2155                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2156                                                 state = f->subclass;
2157                                                 ast_frfree(f);
2158                                                 break;
2159                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
2160                                                 state = f->subclass;
2161                                                 ast_frfree(f);
2162                                                 break;
2163                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
2164                                                 /* Ignore */
2165                                         } else if (f->subclass == -1) {
2166                                                 /* Ignore -- just stopping indications */
2167                                         } else {
2168                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2169                                         }
2170                                 }
2171                                 ast_frfree(f);
2172                         }
2173                 } else
2174                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2175         } else {
2176                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2177                 switch(cause) {
2178                 case AST_CAUSE_BUSY:
2179                         state = AST_CONTROL_BUSY;
2180                         break;
2181                 case AST_CAUSE_CONGESTION:
2182                         state = AST_CONTROL_CONGESTION;
2183                         break;
2184                 }
2185         }
2186         if (chan) {
2187                 /* Final fixups */
2188                 if (oh) {
2189                         if (oh->context && *oh->context)
2190                                 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2191                         if (oh->exten && *oh->exten)
2192                                 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2193                         if (oh->priority)       
2194                                 chan->priority = oh->priority;
2195                 }
2196                 if (chan->_state == AST_STATE_UP) 
2197                         state = AST_CONTROL_ANSWER;
2198         }
2199         if (outstate)
2200                 *outstate = state;
2201         if (chan && res <= 0) {
2202                 if (!chan->cdr) {
2203                         chan->cdr = ast_cdr_alloc();
2204                         if (chan->cdr)
2205                                 ast_cdr_init(chan->cdr, chan);
2206                 }
2207                 if (chan->cdr) {
2208                         char tmp[256];
2209                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
2210                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2211                         ast_cdr_update(chan);
2212                         ast_cdr_start(chan->cdr);
2213                         ast_cdr_end(chan->cdr);
2214                         /* If the cause wasn't handled properly */
2215                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2216                                 ast_cdr_failed(chan->cdr);
2217                 } else 
2218                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2219                 ast_hangup(chan);
2220                 chan = NULL;
2221         }
2222         return chan;
2223 }
2224
2225 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2226 {
2227         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2228 }
2229
2230 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2231 {
2232         struct chanlist *chan;
2233         struct ast_channel *c;
2234         int capabilities;
2235         int fmt;
2236         int res;
2237         int foo;
2238
2239         if (!cause)
2240                 cause = &foo;
2241         *cause = AST_CAUSE_NOTDEFINED;
2242
2243         if (ast_mutex_lock(&chlock)) {
2244                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2245                 return NULL;
2246         }
2247
2248         for (chan = backends; chan; chan = chan->next) {
2249                 if (strcasecmp(type, chan->tech->type))
2250                         continue;
2251
2252                 capabilities = chan->tech->capabilities;
2253                 fmt = format;
2254                 res = ast_translator_best_choice(&fmt, &capabilities);
2255                 if (res < 0) {
2256                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2257                         ast_mutex_unlock(&chlock);
2258                         return NULL;
2259                 }
2260                 ast_mutex_unlock(&chlock);
2261                 if (!chan->tech->requester)
2262                         return NULL;
2263                 
2264                 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2265                         return NULL;
2266
2267                 if (c->_state == AST_STATE_DOWN) {
2268                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2269                                       "Channel: %s\r\n"
2270                                       "State: %s\r\n"
2271                                       "CallerID: %s\r\n"
2272                                       "CallerIDName: %s\r\n"
2273                                       "Uniqueid: %s\r\n",
2274                                       c->name, ast_state2str(c->_state),
2275                                       c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2276                                       c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2277                                       c->uniqueid);
2278                 }
2279                 return c;
2280         }
2281
2282         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2283         *cause = AST_CAUSE_NOSUCHDRIVER;
2284         ast_mutex_unlock(&chlock);
2285
2286         return NULL;
2287 }
2288
2289 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2290 {
2291         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2292            If the remote end does not answer within the timeout, then do NOT hang up, but 
2293            return anyway.  */
2294         int res = -1;
2295         /* Stop if we're a zombie or need a soft hangup */
2296         ast_mutex_lock(&chan->lock);
2297         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2298                 if (chan->tech->call)
2299                         res = chan->tech->call(chan, addr, timeout);
2300         ast_mutex_unlock(&chan->lock);
2301         return res;
2302 }
2303
2304 /*--- ast_transfer: Transfer a call to dest, if the channel supports transfer */
2305 /*      called by app_transfer or the manager interface */
2306 int ast_transfer(struct ast_channel *chan, char *dest) 
2307 {
2308         int res = -1;
2309
2310         /* Stop if we're a zombie or need a soft hangup */
2311         ast_mutex_lock(&chan->lock);
2312         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2313                 if (chan->tech->transfer) {
2314                         res = chan->tech->transfer(chan, dest);
2315                         if (!res)
2316                                 res = 1;
2317                 } else
2318                         res = 0;
2319         }
2320         ast_mutex_unlock(&chan->lock);
2321         return res;
2322 }
2323
2324 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2325 {
2326         int pos=0;
2327         int to = ftimeout;
2328         int d;
2329
2330         /* XXX Merge with full version? XXX */
2331         /* Stop if we're a zombie or need a soft hangup */
2332         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2333                 return -1;
2334         if (!len)
2335                 return -1;
2336         do {
2337                 if (c->stream) {
2338                         d = ast_waitstream(c, AST_DIGIT_ANY);
2339                         ast_stopstream(c);
2340                         usleep(1000);
2341                         if (!d)
2342                                 d = ast_waitfordigit(c, to);
2343                 } else {
2344                         d = ast_waitfordigit(c, to);
2345                 }
2346                 if (d < 0)
2347                         return -1;
2348                 if (d == 0) {
2349                         s[pos]='\0';
2350                         return 1;
2351                 }
2352                 if (!strchr(enders, d))
2353                         s[pos++] = d;
2354                 if (strchr(enders, d) || (pos >= len)) {
2355                         s[pos]='\0';
2356                         return 0;
2357                 }
2358                 to = timeout;
2359         } while(1);
2360         /* Never reached */
2361         return 0;
2362 }
2363
2364 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2365 {
2366         int pos=0;
2367         int to = ftimeout;
2368         int d;
2369
2370         /* Stop if we're a zombie or need a soft hangup */
2371         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2372                 return -1;
2373         if (!len)
2374                 return -1;
2375         do {
2376                 if (c->stream) {
2377                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2378                         ast_stopstream(c);
2379                         usleep(1000);
2380                         if (!d)
2381                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2382                 } else {
2383                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2384                 }
2385                 if (d < 0)
2386                         return -1;
2387                 if (d == 0) {
2388                         s[pos]='\0';
2389                         return 1;
2390                 }
2391                 if (d == 1) {
2392                         s[pos]='\0';
2393                         return 2;
2394                 }
2395                 if (!strchr(enders, d))
2396                         s[pos++] = d;
2397                 if (strchr(enders, d) || (pos >= len)) {
2398                         s[pos]='\0';
2399                         return 0;
2400                 }
2401                 to = timeout;
2402         } while(1);
2403         /* Never reached */
2404         return 0;
2405 }
2406
2407 int ast_channel_supports_html(struct ast_channel *chan)
2408 {
2409         if (chan->tech->send_html)
2410                 return 1;
2411         return 0;
2412 }
2413
2414 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2415 {
2416         if (chan->tech->send_html)
2417                 return chan->tech->send_html(chan, subclass, data, datalen);
2418         return -1;
2419 }
2420
2421 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2422 {
2423         if (chan->tech->send_html)
2424                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2425         return -1;
2426 }
2427
2428 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2429 {
2430         int src;
2431         int dst;
2432
2433         /* Set up translation from the chan to the peer */
2434         src = chan->nativeformats;
2435         dst = peer->nativeformats;
2436         if (ast_translator_best_choice(&dst, &src) < 0) {
2437                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2438                 return -1;
2439         }
2440
2441         /* if the best path is not 'pass through', then
2442            transcoding is needed; if desired, force transcode path
2443            to use SLINEAR between channels */
2444         if ((src != dst) && option_transcode_slin)
2445                 dst = AST_FORMAT_SLINEAR;
2446         if (ast_set_read_format(chan, dst) < 0) {
2447                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2448                 return -1;
2449         }
2450         if (ast_set_write_format(peer, dst) < 0) {
2451                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2452                 return -1;
2453         }
2454
2455         /* Set up translation from the peer to the chan */
2456         src = peer->nativeformats;
2457         dst = chan->nativeformats;
2458         if (ast_translator_best_choice(&dst, &src) < 0) {
2459                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2460                 return -1;
2461         }
2462         /* if the best path is not 'pass through', then
2463            transcoding is needed; if desired, force transcode path
2464            to use SLINEAR between channels */
2465         if ((src != dst) && option_transcode_slin)
2466                 dst = AST_FORMAT_SLINEAR;
2467         if (ast_set_read_format(peer, dst) < 0) {
2468                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2469                 return -1;
2470         }
2471         if (ast_set_write_format(chan, dst) < 0) {
2472                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2473                 return -1;
2474         }
2475         return 0;
2476 }
2477
2478 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2479 {
2480         struct ast_frame null = { AST_FRAME_NULL, };
2481         int res = -1;
2482
2483         if (original == clone) {
2484                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2485                 return -1;
2486         }
2487         ast_mutex_lock(&original->lock);
2488         while(ast_mutex_trylock(&clone->lock)) {
2489                 ast_mutex_unlock(&original->lock);
2490                 usleep(1);
2491                 ast_mutex_lock(&original->lock);
2492         }
2493         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2494                 clone->name, original->name);
2495         if (original->masq) {
2496                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2497                         original->masq->name, original->name);
2498         } else if (clone->masqr) {
2499                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2500                         clone->name, clone->masqr->name);
2501         } else {
2502                 original->masq = clone;
2503                 clone->masqr = original;
2504                 ast_queue_frame(original, &null);
2505                 ast_queue_frame(clone, &null);
2506                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2507                 res = 0;
2508         }
2509         ast_mutex_unlock(&clone->lock);
2510         ast_mutex_unlock(&original->lock);
2511         return res;
2512 }
2513
2514 void ast_change_name(struct ast_channel *chan, char *newname)
2515 {
2516         char tmp[256];
2517         ast_copy_string(tmp, chan->name, sizeof(tmp));
2518         ast_copy_string(chan->name, newname, sizeof(chan->name));
2519         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2520 }
2521
2522 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2523 {
2524         struct ast_var_t *current, *newvar;
2525         char *varname;
2526
2527         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2528                 int vartype = 0;
2529
2530                 varname = ast_var_full_name(current);
2531                 if (!varname)
2532                         continue;
2533
2534                 if (varname[0] == '_') {
2535                         vartype = 1;
2536                         if (varname[1] == '_')
2537                                 vartype = 2;
2538                 }
2539
2540                 switch (vartype) {
2541                 case 1:
2542                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2543                         if (newvar) {
2544                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2545                                 if (option_debug)
2546                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2547                         }
2548                         break;
2549                 case 2:
2550                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2551                         if (newvar) {
2552                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2553                                 if (option_debug)
2554                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2555                         }
2556                         break;
2557                 default:
2558                         if (option_debug)
2559                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2560                         break;
2561                 }
2562         }
2563 }
2564
2565 /* Clone channel variables from 'clone' channel into 'original' channel
2566    All variables except those related to app_groupcount are cloned
2567    Variables are actually _removed_ from 'clone' channel, presumably
2568    because it will subsequently be destroyed.
2569    Assumes locks will be in place on both channels when called.
2570 */
2571    
2572 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2573 {
2574         struct ast_var_t *varptr;
2575
2576         /* we need to remove all app_groupcount related variables from the original
2577            channel before merging in the clone's variables; any groups assigned to the
2578            original channel should be released, only those assigned to the clone
2579            should remain
2580         */
2581
2582         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2583                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2584                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2585                         ast_var_delete(varptr);
2586                 }
2587         }
2588         AST_LIST_TRAVERSE_SAFE_END;
2589
2590         /* Append variables from clone channel into original channel */
2591         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2592         if (AST_LIST_FIRST(&clone->varshead))
2593                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2594 }
2595
2596 /*--- ast_do_masquerade: Masquerade a channel */
2597 /* Assumes channel will be locked when called */
2598 int ast_do_masquerade(struct ast_channel *original)
2599 {
2600         int x,i;
2601         int res=0;
2602         int origstate;
2603         struct ast_frame *cur, *prev;
2604         const struct ast_channel_tech *t;
2605         void *t_pvt;
2606         struct ast_callerid tmpcid;
2607         struct ast_channel *clone = original->masq;
2608         int rformat = original->readformat;
2609         int wformat = original->writeformat;
2610         char newn[100];
2611         char orig[100];
2612         char masqn[100];
2613         char zombn[100];
2614
2615         if (option_debug > 3)
2616                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2617                         clone->name, clone->_state, original->name, original->_state);
2618
2619         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2620            the clone channel into the original channel.  Start by killing off the original
2621            channel's backend.   I'm not sure we're going to keep this function, because 
2622            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2623
2624         /* We need the clone's lock, too */
2625         ast_mutex_lock(&clone->lock);
2626
2627         ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2628
2629         /* Having remembered the original read/write formats, we turn off any translation on either
2630            one */
2631         free_translation(clone);
2632         free_translation(original);
2633
2634
2635         /* Unlink the masquerade */
2636         original->masq = NULL;
2637         clone->masqr = NULL;
2638         
2639         /* Save the original name */
2640         ast_copy_string(orig, original->name, sizeof(orig));
2641         /* Save the new name */
2642         ast_copy_string(newn, clone->name, sizeof(newn));
2643         /* Create the masq name */
2644         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2645                 
2646         /* Copy the name from the clone channel */
2647         ast_copy_string(original->name, newn, sizeof(original->name));
2648
2649         /* Mangle the name of the clone channel */
2650         ast_copy_string(clone->name, masqn, sizeof(clone->name));
2651         
2652         /* Notify any managers of the change, first the masq then the other */
2653         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2654         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2655
2656         /* Swap the technlogies */      
2657         t = original->tech;
2658         original->tech = clone->tech;
2659         clone->tech = t;
2660
2661         t_pvt = original->tech_pvt;
2662         original->tech_pvt = clone->tech_pvt;
2663         clone->tech_pvt = t_pvt;
2664
2665         /* Swap the readq's */
2666         cur = original->readq;
2667         original->readq = clone->readq;
2668         clone->readq = cur;
2669
2670         /* Swap the alertpipes */
2671         for (i = 0; i < 2; i++) {
2672                 x = original->alertpipe[i];
2673                 original->alertpipe[i] = clone->alertpipe[i];
2674                 clone->alertpipe[i] = x;
2675         }
2676
2677         /* Swap the raw formats */
2678         x = original->rawreadformat;
2679         original->rawreadformat = clone->rawreadformat;
2680         clone->rawreadformat = x;
2681         x = original->rawwriteformat;
2682         original->rawwriteformat = clone->rawwriteformat;
2683         clone->rawwriteformat = x;
2684
2685         /* Save any pending frames on both sides.  Start by counting
2686          * how many we're going to need... */
2687         prev = NULL;
2688         cur = clone->readq;
2689         x = 0;
2690         while(cur) {
2691                 x++;
2692                 prev = cur;
2693                 cur = cur->next;
2694         }
2695         /* If we had any, prepend them to the ones already in the queue, and 
2696          * load up the alertpipe */
2697         if (prev) {
2698                 prev->next = original->readq;
2699                 original->readq = clone->readq;
2700                 clone->readq = NULL;
2701                 if (original->alertpipe[1] > -1) {
2702                         for (i = 0; i < x; i++)
2703                                 write(original->alertpipe[1], &x, sizeof(x));
2704                 }
2705         }
2706         clone->_softhangup = AST_SOFTHANGUP_DEV;
2707
2708
2709         /* And of course, so does our current state.  Note we need not
2710            call ast_setstate since the event manager doesn't really consider
2711            these separate.  We do this early so that the clone has the proper
2712            state of the original channel. */
2713         origstate = original->_state;
2714         original->_state = clone->_state;
2715         clone->_state = origstate;
2716
2717         if (clone->tech->fixup){
2718                 res = clone->tech->fixup(original, clone);
2719                 if (res) 
2720                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
2721         }
2722
2723         /* Start by disconnecting the original's physical side */
2724         if (clone->tech->hangup)
2725                 res = clone->tech->hangup(clone);
2726         if (res) {
2727                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
2728                 ast_mutex_unlock(&clone->lock);
2729                 return -1;
2730         }
2731         
2732         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
2733         /* Mangle the name of the clone channel */
2734         ast_copy_string(clone->name, zombn, sizeof(clone->name));
2735         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
2736
2737         /* Update the type. */
2738         original->type = clone->type;
2739         t_pvt = original->monitor;
2740         original->monitor = clone->monitor;
2741         clone->monitor = t_pvt;
2742         
2743         /* Keep the same language.  */
2744         ast_copy_string(original->language, clone->language, sizeof(original->language));
2745         /* Copy the FD's */
2746         for (x = 0; x < AST_MAX_FDS; x++) {
2747                 original->fds[x] = clone->fds[x];
2748         }
2749         clone_variables(original, clone);
2750         clone->varshead.first = NULL;
2751         /* Presense of ADSI capable CPE follows clone */
2752         original->adsicpe = clone->adsicpe;
2753         /* Bridge remains the same */
2754         /* CDR fields remain the same */
2755         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
2756         /* Application and data remain the same */
2757         /* Clone exception  becomes real one, as with fdno */
2758         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
2759         original->fdno = clone->fdno;
2760         /* Schedule context remains the same */
2761         /* Stream stuff stays the same */
2762         /* Keep the original state.  The fixup code will need to work with it most likely */
2763
2764         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
2765            out. */
2766         tmpcid = original->cid;
2767         original->cid = clone->cid;
2768         clone->cid = tmpcid;
2769         
2770         /* Restore original timing file descriptor */
2771         original->fds[AST_MAX_FDS - 2] = original->timingfd;
2772         
2773         /* Our native formats are different now */
2774         original->nativeformats = clone->nativeformats;
2775         
2776         /* Context, extension, priority, app data, jump table,  remain the same */
2777         /* pvt switches.  pbx stays the same, as does next */
2778         
2779         /* Set the write format */
2780         ast_set_write_format(original, wformat);
2781
2782         /* Set the read format */
2783         ast_set_read_format(original, rformat);
2784
2785         /* Copy the music class */
2786         ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
2787
2788         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
2789
2790         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
2791            can fix up everything as best as possible */
2792         if (original->tech->fixup) {
2793                 res = original->tech->fixup(clone, original);
2794                 if (res) {
2795                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
2796                                 original->type, original->name);
2797                         ast_mutex_unlock(&clone->lock);
2798                         return -1;
2799                 }
2800         } else
2801                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
2802                         original->type, original->name);
2803         
2804         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
2805            a zombie so nothing tries to touch it.  If it's already been marked as a
2806            zombie, then free it now (since it already is considered invalid). */
2807         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
2808                 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
2809                 ast_mutex_unlock(&clone->lock);
2810                 ast_channel_free(clone);
2811                 manager_event(EVENT_FLAG_CALL, "Hangup", 
2812                         "Channel: %s\r\n"
2813                         "Uniqueid: %s\r\n"
2814                         "Cause: %d\r\n"
2815                         "Cause-txt: %s\r\n",
2816                         clone->name, 
2817                         clone->uniqueid, 
2818                         clone->hangupcause,
2819                         ast_cause2str(clone->hangupcause)
2820                         );
2821         } else {
2822                 struct ast_frame null_frame = { AST_FRAME_NULL, };
2823                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
2824                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
2825                 ast_queue_frame(clone, &null_frame);
2826                 ast_mutex_unlock(&clone->lock);
2827         }
2828         
2829         /* Signal any blocker */
2830         if (ast_test_flag(original, AST_FLAG_BLOCKING))
2831                 pthread_kill(original->blocker, SIGURG);
2832         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
2833         return 0;
2834 }
2835
2836 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
2837 {
2838         if (callerid) {
2839                 if (chan->cid.cid_num)
2840                         free(chan->cid.cid_num);
2841                 if (ast_strlen_zero(callerid))
2842                         chan->cid.cid_num = NULL;
2843                 else
2844                         chan->cid.cid_num = strdup(callerid);
2845         }
2846         if (calleridname) {
2847                 if (chan->cid.cid_name)
2848                         free(chan->cid.cid_name);
2849                 if (ast_strlen_zero(calleridname))
2850                         chan->cid.cid_name = NULL;
2851                 else
2852                         chan->cid.cid_name = strdup(calleridname);
2853         }
2854         if (ani) {
2855                 if (chan->cid.cid_ani)
2856                         free(chan->cid.cid_ani);
2857                 if (ast_strlen_zero(ani))
2858                         chan->cid.cid_ani = NULL;
2859                 else
2860                         chan->cid.cid_ani = strdup(ani);
2861         }
2862         if (chan->cdr)
2863                 ast_cdr_setcid(chan->cdr, chan);
2864         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
2865                                 "Channel: %s\r\n"
2866                                 "CallerID: %s\r\n"
2867                                 "CallerIDName: %s\r\n"
2868                                 "Uniqueid: %s\r\n"
2869                                 "CID-CallingPres: %d (%s)\r\n",
2870                                 chan->name, chan->cid.cid_num ? 
2871                                 chan->cid.cid_num : "<Unknown>",
2872                                 chan->cid.cid_name ? 
2873                                 chan->cid.cid_name : "<Unknown>",
2874                                 chan->uniqueid,
2875                                 chan->cid.cid_pres,
2876                                 ast_describe_caller_presentation(chan->cid.cid_pres)
2877                                 );
2878 }
2879
2880 int ast_setstate(struct ast_channel *chan, int state)
2881 {
2882         int oldstate = chan->_state;
2883
2884         if (oldstate == state)
2885                 return 0;
2886
2887         chan->_state = state;
2888         ast_device_state_changed(chan->name);
2889         manager_event(EVENT_FLAG_CALL,
2890                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
2891                       "Channel: %s\r\n"
2892                       "State: %s\r\n"
2893                       "CallerID: %s\r\n"
2894                       "CallerIDName: %s\r\n"
2895                       "Uniqueid: %s\r\n",
2896                       chan->name, ast_state2str(chan->_state), 
2897                       chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
2898                       chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
2899                       chan->uniqueid);
2900
2901         return 0;
2902 }
2903
2904 /*--- Find bridged channel */
2905 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
2906 {
2907         struct ast_channel *bridged;
2908         bridged = chan->_bridge;
2909         if (bridged && bridged->tech->bridged_channel) 
2910                 bridged = bridged->tech->bridged_channel(chan, bridged);
2911         return bridged;
2912 }
2913
2914 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, char *sound, int remain) 
2915 {
2916         int res=0, min=0, sec=0,check=0;
2917
2918         check = ast_autoservice_start(peer);
2919         if(check) 
2920                 return;
2921
2922         if (remain > 0) {
2923                 if (remain / 60 > 1) {
2924                         min = remain / 60;
2925                         sec = remain % 60;
2926                 } else {
2927                         sec = remain;
2928                 }
2929         }
2930         
2931         if (!strcmp(sound,"timeleft")) {        /* Queue support */
2932                 res = ast_streamfile(chan, "vm-youhave", chan->language);
2933                 res = ast_waitstream(chan, "");
2934                 if (min) {
2935                         res = ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
2936                         res = ast_streamfile(chan, "queue-minutes", chan->language);
2937                         res = ast_waitstream(chan, "");
2938                 }
2939                 if (sec) {
2940                         res = ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
2941                         res = ast_streamfile(chan, "queue-seconds", chan->language);
2942                         res = ast_waitstream(chan, "");
2943                 }
2944         } else {
2945                 res = ast_streamfile(chan, sound, chan->language);
2946                 res = ast_waitstream(chan, "");
2947         }
2948
2949         check = ast_autoservice_stop(peer);
2950 }
2951
2952 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
2953                               struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc, int toms)
2954 {
2955         /* Copy voice back and forth between the two channels. */
2956         struct ast_channel *cs[3];
2957         struct ast_frame *f;
2958         struct ast_channel *who = NULL;
2959         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
2960         int o0nativeformats;
2961         int o1nativeformats;
2962         int watch_c0_dtmf;
2963         int watch_c1_dtmf;
2964         void *pvt0, *pvt1;
2965         
2966         cs[0] = c0;
2967         cs[1] = c1;
2968         pvt0 = c0->tech_pvt;
2969         pvt1 = c1->tech_pvt;
2970         o0nativeformats = c0->nativeformats;
2971         o1nativeformats = c1->nativeformats;
2972         watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
2973         watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
2974
2975         for (;;) {
2976                 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
2977                     (o0nativeformats != c0->nativeformats) ||
2978                     (o1nativeformats != c1->nativeformats)) {
2979                         /* Check for Masquerade, codec changes, etc */
2980                         res = AST_BRIDGE_RETRY;
2981                         break;
2982                 }
2983                 who = ast_waitfor_n(cs, 2, &toms);
2984                 if (!who) {
2985                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
2986                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
2987                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2988                                         c0->_softhangup = 0;
2989                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
2990                                         c1->_softhangup = 0;
2991                                 c0->_bridge = c1;
2992                                 c1->_bridge = c0;
2993                         }
2994                         continue;
2995                 }
2996                 f = ast_read(who);
2997                 if (!f) {
2998                         *fo = NULL;
2999                         *rc = who;
3000                         res = AST_BRIDGE_COMPLETE;
3001                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3002                         break;
3003                 }
3004
3005                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3006                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
3007                             (f->subclass == AST_CONTROL_VIDUPDATE)) {
3008                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
3009                         } else {
3010                                 *fo = f;
3011                                 *rc = who;
3012                                 res =  AST_BRIDGE_COMPLETE;
3013                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3014                                 break;
3015                         }
3016                 }
3017                 if ((f->frametype == AST_FRAME_VOICE) ||
3018                     (f->frametype == AST_FRAME_DTMF) ||
3019                     (f->frametype == AST_FRAME_VIDEO) || 
3020                     (f->frametype == AST_FRAME_IMAGE) ||
3021                     (f->frametype == AST_FRAME_HTML) ||
3022                     (f->frametype == AST_FRAME_TEXT)) {
3023                         if (f->frametype == AST_FRAME_DTMF) {
3024                                 if (((who == c0) && watch_c0_dtmf) ||
3025                                     ((who == c1) && watch_c1_dtmf)) {
3026                                         *rc = who;
3027                                         *fo = f;
3028                                         res = AST_BRIDGE_COMPLETE;
3029                                         ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3030                                         break;
3031                                 } else {
3032                                         goto tackygoto;
3033                                 }
3034                         } else {
3035 #if 0
3036                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3037                                 if (who == last) 
3038                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3039                                 last = who;
3040 #endif
3041 tackygoto:
3042                                 ast_write((who == c0) ? c1 : c0, f);
3043                         }
3044                 }
3045                 ast_frfree(f);
3046
3047                 /* Swap who gets priority */
3048                 cs[2] = cs[0];
3049                 cs[0] = cs[1];
3050                 cs[1] = cs[2];
3051         }
3052         return res;
3053 }
3054
3055 /*--- ast_channel_bridge: Bridge two channels together */
3056 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3057                                           struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc) 
3058 {
3059         struct ast_channel *who = NULL;
3060         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3061         int nativefailed=0;
3062         int firstpass;
3063         int o0nativeformats;
3064         int o1nativeformats;
3065         long time_left_ms=0;
3066         struct timeval nexteventts = { 0, };
3067         char caller_warning = 0;
3068         char callee_warning = 0;
3069         int to;
3070
3071         if (c0->_bridge) {
3072                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3073                         c0->name, c0->_bridge->name);
3074                 return -1;
3075         }
3076         if (c1->_bridge) {
3077                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3078                         c1->name, c1->_bridge->name);
3079                 return -1;
3080         }
3081         
3082         /* Stop if we're a zombie or need a soft hangup */
3083         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3084             ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) 
3085                 return -1;
3086
3087         *fo = NULL;
3088         firstpass = config->firstpass;
3089         config->firstpass = 0;
3090
3091         if (ast_tvzero(config->start_time))
3092                 config->start_time = ast_tvnow();
3093         time_left_ms = config->timelimit;
3094
3095         caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3096         callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3097
3098         if (config->start_sound && firstpass) {
3099                 if (caller_warning)
3100                         bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3101                 if (callee_warning)
3102                         bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3103         }
3104
3105         /* Keep track of bridge */
3106         c0->_bridge = c1;
3107         c1->_bridge = c0;
3108         
3109         manager_event(EVENT_FLAG_CALL, "Link", 
3110                       "Channel1: %s\r\n"
3111                       "Channel2: %s\r\n"
3112                       "Uniqueid1: %s\r\n"
3113                       "Uniqueid2: %s\r\n"
3114                       "CallerID1: %s\r\n"
3115                       "CallerID2: %s\r\n",
3116                       c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3117                                                                         
3118         o0nativeformats = c0->nativeformats;
3119         o1nativeformats = c1->nativeformats;
3120
3121         if (config->timelimit) {
3122                 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3123                 if (caller_warning || callee_warning)
3124                         nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3125         }
3126
3127         for (/* ever */;;) {
3128                 to = -1;
3129                 if (config->timelimit) {
3130                         struct timeval now;
3131                         now = ast_tvnow();
3132                         to = ast_tvdiff_ms(nexteventts, now);
3133                         if (to < 0)
3134                                 to = 0;
3135                         time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3136                         if (time_left_ms < to)
3137                                 to = time_left_ms;
3138
3139                         if (time_left_ms <= 0) {
3140                                 if (caller_warning && config->end_sound)
3141                                         bridge_playfile(c0, c1, config->end_sound, 0);
3142                                 if (callee_warning && config->end_sound)
3143                                         bridge_playfile(c1, c0, config->end_sound, 0);
3144                                 *fo = NULL;
3145                                 if (who) 
3146                                         *rc = who;
3147                                 res = 0;
3148                                 break;
3149                         }
3150                         
3151                         if (!to) {
3152                                 if (time_left_ms >= 5000) {
3153                                         if (caller_warning && config->warning_sound && config->play_warning)
3154                                                 bridge_playfile(c0, c1, config->warning_sound, time_left_ms / 1000);
3155                                         if (callee_warning && config->warning_sound && config->play_warning)
3156                                                 bridge_playfile(c1, c0, config->warning_sound, time_left_ms / 1000);
3157                                 }
3158                                 if (config->warning_freq) {
3159                                         nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3160                                 } else
3161                                         nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3162                         }
3163                 }
3164
3165                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3166                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3167                                 c0->_softhangup = 0;
3168                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3169                                 c1->_softhangup = 0;
3170                         c0->_bridge = c1;
3171                         c1->_bridge = c0;
3172                         ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3173                         continue;
3174                 }
3175                 
3176                 /* Stop if we're a zombie or need a soft hangup */
3177                 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3178                     ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3179                         *fo = NULL;
3180                         if (who)
3181                                 *rc = who;
3182                         res = 0;
3183                         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",
3184                                 c0->name, c1->name,
3185                                 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3186                                 ast_check_hangup(c0) ? "Yes" : "No",
3187                                 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3188                                 ast_check_hangup(c1) ? "Yes" : "No");
3189                         break;
3190                 }
3191
3192                 if (c0->tech->bridge &&
3193                     (config->timelimit == 0) &&
3194                     (c0->tech->bridge == c1->tech->bridge) &&
3195                     !nativefailed && !c0->monitor && !c1->monitor && !c0->spiers && !c1->spiers) {
3196                         /* Looks like they share a bridge method */
3197                         if (option_verbose > 2) 
3198                                 ast_verbose(VERBOSE_PREFIX_3 "Attempting native bridge of %s and %s\n", c0->name, c1->name);
3199                         ast_set_flag(c0, AST_FLAG_NBRIDGE);
3200                         ast_set_flag(c1, AST_FLAG_NBRIDGE);
3201                         if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
3202                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
3203                                               "Channel1: %s\r\n"
3204                                               "Channel2: %s\r\n"
3205                                               "Uniqueid1: %s\r\n"
3206                                               "Uniqueid2: %s\r\n"
3207                                               "CallerID1: %s\r\n"
3208                                               "CallerID2: %s\r\n",
3209                                               c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3210                                 ast_log(LOG_DEBUG, "Returning from native bridge, channels: %s, %s\n", c0->name, c1->name);
3211
3212                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3213                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3214
3215                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3216                                         continue;
3217
3218                                 c0->_bridge = NULL;
3219                                 c1->_bridge = NULL;
3220
3221                                 return res;
3222                         } else {
3223                                 ast_clear_flag(c0, AST_FLAG_NBRIDGE);
3224                                 ast_clear_flag(c1, AST_FLAG_NBRIDGE);
3225                         }
3226                         
3227                         switch (res) {
3228                         case AST_BRIDGE_RETRY:
3229 /*                              continue; */
3230                                 break;
3231                         default:
3232                                 ast_log(LOG_WARNING, "Private bridge between %s and %s failed\n", c0->name, c1->name);
3233                                 /* fallthrough */
3234                         case AST_BRIDGE_FAILED_NOWARN:
3235                                 nativefailed++;
3236                                 break;
3237                         }
3238                 }
3239         
3240                 if (((c0->writeformat != c1->readformat) || (c0->readformat != c1->writeformat) ||
3241                     (c0->nativeformats != o0nativeformats) || (c1->nativeformats != o1nativeformats)) &&
3242                     !(c0->generator || c1->generator)) {
3243                         if (ast_channel_make_compatible(c0, c1)) {
3244                                 ast_log(LOG_WARNING, "Can't make %s and %s compatible\n", c0->name, c1->name);
3245                                 manager_event(EVENT_FLAG_CALL, "Unlink",
3246                                               "Channel1: %s\r\n"
3247                                               "Channel2: %s\r\n"
3248                                               "Uniqueid1: %s\r\n"
3249                                               "Uniqueid2: %s\r\n"
3250                                               "CallerID1: %s\r\n"
3251                                               "CallerID2: %s\r\n",
3252                                               c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3253                                 return AST_BRIDGE_FAILED;
3254                         }
3255                         o0nativeformats = c0->nativeformats;
3256                         o1nativeformats = c1->nativeformats;
3257                 }
3258                 res = ast_generic_bridge(c0, c1, config, fo, rc, to);
3259                 if (res != AST_BRIDGE_RETRY)
3260                         break;
3261         }
3262
3263         c0->_bridge = NULL;
3264         c1->_bridge = NULL;
3265
3266         manager_event(EVENT_FLAG_CALL, "Unlink",
3267                       "Channel1: %s\r\n"
3268                       "Channel2: %s\r\n"
3269                       "Uniqueid1: %s\r\n"
3270                       "Uniqueid2: %s\r\n"
3271                       "CallerID1: %s\r\n"
3272                       "CallerID2: %s\r\n",
3273                       c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3274         ast_log(LOG_DEBUG, "Bridge stops bridging channels %s and %s\n", c0->name, c1->name);
3275
3276         return res;
3277 }
3278
3279 /*--- ast_channel_setoption: Sets an option on a channel */
3280 int ast_channel_setoption(struct ast_channel *chan, int option, void *data, int datalen, int block)
3281 {
3282         int res;
3283
3284         if (chan->tech->setoption) {
3285                 res = chan->tech->setoption(chan, option, data, datalen);
3286                 if (res < 0)
3287                         return res;
3288         } else {
3289                 errno = ENOSYS;
3290                 return -1;
3291         }
3292         if (block) {
3293                 /* XXX Implement blocking -- just wait for our option frame reply, discarding
3294                    intermediate packets. XXX */
3295                 ast_log(LOG_ERROR, "XXX Blocking not implemented yet XXX\n");
3296                 return -1;
3297         }
3298         return 0;
3299 }
3300
3301 struct tonepair_def {
3302         int freq1;
3303         int freq2;
3304         int duration;
3305         int vol;
3306 };
3307
3308 struct tonepair_state {
3309         float freq1;
3310         float freq2;
3311         float vol;
3312         int duration;
3313         int pos;
3314         int origwfmt;
3315         struct ast_frame f;
3316         unsigned char offset[AST_FRIENDLY_OFFSET];
3317         short data[4000];
3318 };
3319
3320 static void tonepair_release(struct ast_channel *chan, void *params)
3321 {
3322         struct tonepair_state *ts = params;
3323
3324         if (chan) {
3325                 ast_set_write_format(chan, ts->origwfmt);
3326         }
3327         free(ts);
3328 }
3329
3330 static void *tonepair_alloc(struct ast_channel *chan, void *params)
3331 {
3332         struct tonepair_state *ts;
3333         struct tonepair_def *td = params;
3334
3335         ts = malloc(sizeof(struct tonepair_state));
3336         if (!ts)
3337                 return NULL;
3338         memset(ts, 0, sizeof(struct tonepair_state));
3339         ts->origwfmt = chan->writeformat;
3340         if (ast_set_write_format(chan, AST_FORMAT_SLINEAR)) {
3341                 ast_log(LOG_WARNING, "Unable to set '%s' to signed linear format (write)\n", chan->name);
3342                 tonepair_release(NULL, ts);
3343                 ts = NULL;
3344         } else {
3345                 ts->freq1 = td->freq1;
3346                 ts->freq2 = td->freq2;
3347                 ts->duration = td->duration;
3348                 ts->vol = td->vol;
3349         }
3350         /* Let interrupts interrupt :) */
3351         ast_set_flag(chan, AST_FLAG_WRITE_INT);
3352         return ts;
3353 }
3354
3355 static int tonepair_generator(struct ast_channel *chan, void *data, int len, int samples)
3356 {
3357         struct tonepair_state *ts = data;
3358         int x;
3359
3360         /* we need to prepare a frame with 16 * timelen samples as we're 
3361          * generating SLIN audio
3362          */
3363         len = samples * 2;
3364
3365         if (len > sizeof(ts->data) / 2 - 1) {
3366                 ast_log(LOG_WARNING, "Can't generate that much data!\n");
3367                 return -1;
3368         }
3369         memset(&ts->f, 0, sizeof(ts->f));
3370         for (x = 0; x < (len / 2); x++) {
3371                 ts->data[x] = ts->vol * (
3372                                 sin((ts->freq1 * 2.0 * M_PI / 8000.0) * (ts->pos + x)) +
3373                                 sin((ts->freq2 * 2.0 * M_PI / 8000.0) * (ts->pos + x))
3374                         );
3375         }
3376         ts->f.frametype = AST_FRAME_VOICE;
3377         ts->f.subclass = AST_FORMAT_SLINEAR;
3378         ts->f.datalen = len;
3379         ts->f.samples = samples;
3380         ts->f.offset = AST_FRIENDLY_OFFSET;
3381         ts->f.data = ts->data;
3382         ast_write(chan, &ts->f);
3383         ts->pos += x;
3384         if (ts->duration > 0) {
3385                 if (ts->pos >= ts->duration * 8)
3386                         return -1;
3387         }
3388         return 0;
3389 }
3390
3391 static struct ast_generator tonepair = {
3392         alloc: tonepair_alloc,
3393         release: tonepair_release,
3394         generate: tonepair_generator,
3395 };
3396
3397 int ast_tonepair_start(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3398 {
3399         struct tonepair_def d = { 0, };
3400
3401         d.freq1 = freq1;
3402         d.freq2 = freq2;
3403         d.duration = duration;
3404         if (vol < 1)
3405                 d.vol = 8192;
3406         else
3407                 d.vol = vol;
3408         if (ast_activate_generator(chan, &tonepair, &d))
3409                 return -1;
3410         return 0;
3411 }
3412
3413 void ast_tonepair_stop(struct ast_channel *chan)
3414 {
3415         ast_deactivate_generator(chan);
3416 }
3417
3418 int ast_tonepair(struct ast_channel *chan, int freq1, int freq2, int duration, int vol)
3419 {
3420         struct ast_frame *f;
3421         int res;
3422
3423         if ((res = ast_tonepair_start(chan, freq1, freq2, duration, vol)))
3424                 return res;
3425
3426         /* Give us some wiggle room */
3427         while(chan->generatordata && (ast_waitfor(chan, 100) >= 0)) {
3428                 f = ast_read(chan);
3429                 if (f)
3430                         ast_frfree(f);
3431                 else
3432                         return -1;
3433         }
3434         return 0;
3435 }
3436
3437 ast_group_t ast_get_group(char *s)
3438 {
3439         char *copy;
3440         char *piece;
3441         char *c=NULL;
3442         int start=0, finish=0, x;
3443         ast_group_t group = 0;
3444
3445         copy = ast_strdupa(s);
3446         if (!copy) {
3447                 ast_log(LOG_ERROR, "Out of memory\n");
3448                 return 0;
3449         }
3450         c = copy;
3451         
3452         while((piece = strsep(&c, ","))) {
3453                 if (sscanf(piece, "%d-%d", &start, &finish) == 2) {
3454                         /* Range */
3455                 } else if (sscanf(piece, "%d", &start)) {
3456                         /* Just one */
3457                         finish = start;
3458                 } else {
3459                         ast_log(LOG_ERROR, "Syntax error parsing group configuration '%s' at '%s'. Ignoring.\n", s, piece);
3460                         continue;
3461                 }
3462                 for (x = start; x <= finish; x++) {
3463                         if ((x > 63) || (x < 0)) {
3464                                 ast_log(LOG_WARNING, "Ignoring invalid group %d (maximum group is 63)\n", x);
3465                         } else
3466                                 group |= ((ast_group_t) 1 << x);
3467                 }
3468         }
3469         return group;
3470 }
3471
3472 static int (*ast_moh_start_ptr)(struct ast_channel *, char *) = NULL;
3473 static void (*ast_moh_stop_ptr)(struct ast_channel *) = NULL;
3474 static void (*ast_moh_cleanup_ptr)(struct ast_channel *) = NULL;
3475
3476
3477 void ast_install_music_functions(int (*start_ptr)(struct ast_channel *, char *),
3478                                                                  void (*stop_ptr)(struct ast_channel *),
3479                                                                  void (*cleanup_ptr)(struct ast_channel *)
3480                                                                  ) 
3481 {
3482         ast_moh_start_ptr = start_ptr;
3483         ast_moh_stop_ptr = stop_ptr;
3484         ast_moh_cleanup_ptr = cleanup_ptr;
3485 }
3486
3487 void ast_uninstall_music_functions(void) 
3488 {
3489         ast_moh_start_ptr = NULL;
3490         ast_moh_stop_ptr = NULL;
3491         ast_moh_cleanup_ptr = NULL;
3492 }
3493
3494 /*! Turn on music on hold on a given channel */
3495 int ast_moh_start(struct ast_channel *chan, char *mclass) 
3496 {
3497         if (ast_moh_start_ptr)
3498                 return ast_moh_start_ptr(chan, mclass);
3499
3500         if (option_verbose > 2)
3501                 ast_verbose(VERBOSE_PREFIX_3 "Music class %s requested but no musiconhold loaded.\n", mclass ? mclass : "default");
3502         
3503         return 0;
3504 }
3505
3506 /*! Turn off music on hold on a given channel */
3507 void ast_moh_stop(struct ast_channel *chan) 
3508 {
3509         if(ast_moh_stop_ptr)
3510                 ast_moh_stop_ptr(chan);
3511 }
3512
3513 void ast_moh_cleanup(struct ast_channel *chan) 
3514 {
3515         if(ast_moh_cleanup_ptr)
3516         ast_moh_cleanup_ptr(chan);
3517 }
3518
3519 void ast_channels_init(void)
3520 {
3521         ast_cli_register(&cli_show_channeltypes);
3522 }
3523
3524 /*--- ast_print_group: Print call group and pickup group ---*/
3525 char *ast_print_group(char *buf, int buflen, ast_group_t group) 
3526 {
3527         unsigned int i;
3528         int first=1;
3529         char num[3];
3530
3531         buf[0] = '\0';
3532         
3533         if (!group)     /* Return empty string if no group */
3534                 return(buf);
3535
3536         for (i=0; i<=63; i++) { /* Max group is 63 */
3537                 if (group & ((ast_group_t) 1 << i)) {
3538                         if (!first) {
3539                                 strncat(buf, ", ", buflen);
3540                         } else {
3541                                 first=0;
3542                         }
3543                         snprintf(num, sizeof(num), "%u", i);
3544                         strncat(buf, num, buflen);
3545                 }
3546         }
3547         return(buf);
3548 }
3549
3550 void ast_set_variables(struct ast_channel *chan, struct ast_variable *vars)
3551 {
3552         struct ast_variable *cur;
3553
3554         for (cur = vars; cur; cur = cur->next)
3555                 pbx_builtin_setvar_helper(chan, cur->name, cur->value); 
3556 }