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