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