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