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