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