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