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