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