952c7b6ad95906bdce9d8fab14c71b2eb5ad1393
[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
2493         if ((*rawformat == native) && (*format == fmt)) {
2494                 /* the channel is already in these formats, so nothing to do */
2495                 ast_channel_unlock(chan);
2496                 return 0;
2497         }
2498
2499         *rawformat = native;
2500         /* User perspective is fmt */
2501         *format = fmt;
2502         /* Free any read translation we have right now */
2503         if (*trans)
2504                 ast_translator_free_path(*trans);
2505         /* Build a translation path from the raw format to the desired format */
2506         if (!direction)
2507                 /* reading */
2508                 *trans = ast_translator_build_path(*format, *rawformat);
2509         else
2510                 /* writing */
2511                 *trans = ast_translator_build_path(*rawformat, *format);
2512         ast_channel_unlock(chan);
2513         if (option_debug)
2514                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2515                         direction ? "write" : "read", ast_getformatname(fmt));
2516         return 0;
2517 }
2518
2519 int ast_set_read_format(struct ast_channel *chan, int fmt)
2520 {
2521         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2522                           &chan->readtrans, 0);
2523 }
2524
2525 int ast_set_write_format(struct ast_channel *chan, int fmt)
2526 {
2527         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2528                           &chan->writetrans, 1);
2529 }
2530
2531 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)
2532 {
2533         int dummy_outstate;
2534         int cause = 0;
2535         struct ast_channel *chan;
2536         int res = 0;
2537         
2538         if (outstate)
2539                 *outstate = 0;
2540         else
2541                 outstate = &dummy_outstate;     /* make outstate always a valid pointer */
2542
2543         chan = ast_request(type, format, data, &cause);
2544         if (!chan) {
2545                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2546                 /* compute error and return */
2547                 if (cause == AST_CAUSE_BUSY)
2548                         *outstate = AST_CONTROL_BUSY;
2549                 else if (cause == AST_CAUSE_CONGESTION)
2550                         *outstate = AST_CONTROL_CONGESTION;
2551                 return NULL;
2552         }
2553
2554         if (oh) {
2555                 if (oh->vars)   
2556                         ast_set_variables(chan, oh->vars);
2557                 /* XXX why is this necessary, for the parent_channel perhaps ? */
2558                 if (!ast_strlen_zero(oh->cid_num) && !ast_strlen_zero(oh->cid_name))
2559                         ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2560                 if (oh->parent_channel)
2561                         ast_channel_inherit_variables(oh->parent_channel, chan);
2562                 if (oh->account)
2563                         ast_cdr_setaccount(chan, oh->account);  
2564         }
2565         ast_set_callerid(chan, cid_num, cid_name, cid_num);
2566
2567         if (ast_call(chan, data, 0)) {  /* ast_call failed... */
2568                 ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2569         } else {
2570                 res = 1;        /* mark success in case chan->_state is already AST_STATE_UP */
2571                 while (timeout && chan->_state != AST_STATE_UP) {
2572                         struct ast_frame *f;
2573                         res = ast_waitfor(chan, timeout);
2574                         if (res <= 0) /* error, timeout, or done */
2575                                 break;
2576                         if (timeout > -1)
2577                                 timeout = res;
2578                         f = ast_read(chan);
2579                         if (!f) {
2580                                 *outstate = AST_CONTROL_HANGUP;
2581                                 res = 0;
2582                                 break;
2583                         }
2584                         if (f->frametype == AST_FRAME_CONTROL) {
2585                                 switch (f->subclass) {
2586                                 case AST_CONTROL_RINGING:       /* record but keep going */
2587                                         *outstate = f->subclass;
2588                                         break;
2589
2590                                 case AST_CONTROL_BUSY:
2591                                 case AST_CONTROL_CONGESTION:
2592                                 case AST_CONTROL_ANSWER:
2593                                         *outstate = f->subclass;
2594                                         timeout = 0;            /* trick to force exit from the while() */
2595                                         break;
2596
2597                                 /* Ignore these */
2598                                 case AST_CONTROL_PROGRESS:
2599                                 case AST_CONTROL_PROCEEDING:
2600                                 case AST_CONTROL_HOLD:
2601                                 case AST_CONTROL_UNHOLD:
2602                                 case AST_CONTROL_VIDUPDATE:
2603                                 case -1:                        /* Ignore -- just stopping indications */
2604                                         break;
2605
2606                                 default:
2607                                         ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2608                                 }
2609                         }
2610                         ast_frfree(f);
2611                 }
2612         }
2613
2614         /* Final fixups */
2615         if (oh) {
2616                 if (!ast_strlen_zero(oh->context))
2617                         ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2618                 if (!ast_strlen_zero(oh->exten))
2619                         ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2620                 if (oh->priority)       
2621                         chan->priority = oh->priority;
2622         }
2623         if (chan->_state == AST_STATE_UP)
2624                 *outstate = AST_CONTROL_ANSWER;
2625
2626         if (res <= 0) {
2627                 if (!chan->cdr && (chan->cdr = ast_cdr_alloc()))
2628                         ast_cdr_init(chan->cdr, chan);
2629                 if (chan->cdr) {
2630                         char tmp[256];
2631                         snprintf(tmp, sizeof(tmp), "%s/%s", type, (char *)data);
2632                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2633                         ast_cdr_update(chan);
2634                         ast_cdr_start(chan->cdr);
2635                         ast_cdr_end(chan->cdr);
2636                         /* If the cause wasn't handled properly */
2637                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2638                                 ast_cdr_failed(chan->cdr);
2639                 }
2640                 ast_hangup(chan);
2641                 chan = NULL;
2642         }
2643         return chan;
2644 }
2645
2646 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2647 {
2648         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2649 }
2650
2651 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2652 {
2653         struct chanlist *chan;
2654         struct ast_channel *c;
2655         int capabilities;
2656         int fmt;
2657         int res;
2658         int foo;
2659         int videoformat = format & AST_FORMAT_VIDEO_MASK;
2660
2661         if (!cause)
2662                 cause = &foo;
2663         *cause = AST_CAUSE_NOTDEFINED;
2664
2665         if (AST_LIST_LOCK(&channels)) {
2666                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2667                 return NULL;
2668         }
2669
2670         AST_LIST_TRAVERSE(&backends, chan, list) {
2671                 if (strcasecmp(type, chan->tech->type))
2672                         continue;
2673
2674                 capabilities = chan->tech->capabilities;
2675                 fmt = format & AST_FORMAT_AUDIO_MASK;
2676                 res = ast_translator_best_choice(&fmt, &capabilities);
2677                 if (res < 0) {
2678                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2679                         AST_LIST_UNLOCK(&channels);
2680                         return NULL;
2681                 }
2682                 AST_LIST_UNLOCK(&channels);
2683                 if (!chan->tech->requester)
2684                         return NULL;
2685                 
2686                 if (!(c = chan->tech->requester(type, capabilities | videoformat, data, cause)))
2687                         return NULL;
2688
2689                 if (c->_state == AST_STATE_DOWN) {
2690                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2691                                       "Channel: %s\r\n"
2692                                       "State: %s\r\n"
2693                                       "CallerID: %s\r\n"
2694                                       "CallerIDName: %s\r\n"
2695                                       "Uniqueid: %s\r\n",
2696                                       c->name, ast_state2str(c->_state),
2697                                       S_OR(c->cid.cid_num, "<unknown>"),
2698                                       S_OR(c->cid.cid_name, "<unknown>"),
2699                                       c->uniqueid);
2700                 }
2701                 return c;
2702         }
2703
2704         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2705         *cause = AST_CAUSE_NOSUCHDRIVER;
2706         AST_LIST_UNLOCK(&channels);
2707
2708         return NULL;
2709 }
2710
2711 int ast_call(struct ast_channel *chan, char *addr, int timeout)
2712 {
2713         /* Place an outgoing call, but don't wait any longer than timeout ms before returning.
2714            If the remote end does not answer within the timeout, then do NOT hang up, but
2715            return anyway.  */
2716         int res = -1;
2717         /* Stop if we're a zombie or need a soft hangup */
2718         ast_channel_lock(chan);
2719         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2720                 if (chan->tech->call)
2721                         res = chan->tech->call(chan, addr, timeout);
2722                 ast_set_flag(chan, AST_FLAG_OUTGOING);
2723         }
2724         ast_channel_unlock(chan);
2725         return res;
2726 }
2727
2728 /*!
2729   \brief Transfer a call to dest, if the channel supports transfer
2730
2731   Called by:
2732     \arg app_transfer
2733     \arg the manager interface
2734 */
2735 int ast_transfer(struct ast_channel *chan, char *dest)
2736 {
2737         int res = -1;
2738
2739         /* Stop if we're a zombie or need a soft hangup */
2740         ast_channel_lock(chan);
2741         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2742                 if (chan->tech->transfer) {
2743                         res = chan->tech->transfer(chan, dest);
2744                         if (!res)
2745                                 res = 1;
2746                 } else
2747                         res = 0;
2748         }
2749         ast_channel_unlock(chan);
2750         return res;
2751 }
2752
2753 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2754 {
2755         return ast_readstring_full(c, s, len, timeout, ftimeout, enders, -1, -1);
2756 }
2757
2758 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2759 {
2760         int pos = 0;    /* index in the buffer where we accumulate digits */
2761         int to = ftimeout;
2762
2763         /* Stop if we're a zombie or need a soft hangup */
2764         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c))
2765                 return -1;
2766         if (!len)
2767                 return -1;
2768         for (;;) {
2769                 int d;
2770                 if (c->stream) {
2771                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2772                         ast_stopstream(c);
2773                         usleep(1000);
2774                         if (!d)
2775                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2776                 } else {
2777                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2778                 }
2779                 if (d < 0)
2780                         return -1;
2781                 if (d == 0) {
2782                         s[pos]='\0';
2783                         return 1;
2784                 }
2785                 if (d == 1) {
2786                         s[pos]='\0';
2787                         return 2;
2788                 }
2789                 if (!strchr(enders, d))
2790                         s[pos++] = d;
2791                 if (strchr(enders, d) || (pos >= len)) {
2792                         s[pos]='\0';
2793                         return 0;
2794                 }
2795                 to = timeout;
2796         }
2797         /* Never reached */
2798         return 0;
2799 }
2800
2801 int ast_channel_supports_html(struct ast_channel *chan)
2802 {
2803         return (chan->tech->send_html) ? 1 : 0;
2804 }
2805
2806 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2807 {
2808         if (chan->tech->send_html)
2809                 return chan->tech->send_html(chan, subclass, data, datalen);
2810         return -1;
2811 }
2812
2813 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2814 {
2815         return ast_channel_sendhtml(chan, AST_HTML_URL, url, strlen(url) + 1);
2816 }
2817
2818 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2819 {
2820         int src;
2821         int dst;
2822
2823         /* Set up translation from the chan to the peer */
2824         src = chan->nativeformats;
2825         dst = peer->nativeformats;
2826         if (ast_translator_best_choice(&dst, &src) < 0) {
2827                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2828                 return -1;
2829         }
2830
2831         /* if the best path is not 'pass through', then
2832            transcoding is needed; if desired, force transcode path
2833            to use SLINEAR between channels, but only if there is
2834            no direct conversion available */
2835         if ((src != dst) && ast_opt_transcode_via_slin &&
2836             (ast_translate_path_steps(dst, src) != 1))
2837                 dst = AST_FORMAT_SLINEAR;
2838         if (ast_set_read_format(chan, dst) < 0) {
2839                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2840                 return -1;
2841         }
2842         if (ast_set_write_format(peer, dst) < 0) {
2843                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2844                 return -1;
2845         }
2846
2847         /* Set up translation from the peer to the chan */
2848         src = peer->nativeformats;
2849         dst = chan->nativeformats;
2850         if (ast_translator_best_choice(&dst, &src) < 0) {
2851                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2852                 return -1;
2853         }
2854
2855         /* if the best path is not 'pass through', then
2856            transcoding is needed; if desired, force transcode path
2857            to use SLINEAR between channels, but only if there is
2858            no direct conversion available */
2859         if ((src != dst) && ast_opt_transcode_via_slin &&
2860             (ast_translate_path_steps(dst, src) != 1))
2861                 dst = AST_FORMAT_SLINEAR;
2862         if (ast_set_read_format(peer, dst) < 0) {
2863                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2864                 return -1;
2865         }
2866         if (ast_set_write_format(chan, dst) < 0) {
2867                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2868                 return -1;
2869         }
2870         return 0;
2871 }
2872
2873 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2874 {
2875         int res = -1;
2876         struct ast_channel *final_orig = original, *final_clone = clone;
2877
2878         ast_channel_lock(original);
2879         while (ast_channel_trylock(clone)) {
2880                 ast_channel_unlock(original);
2881                 usleep(1);
2882                 ast_channel_lock(original);
2883         }
2884
2885         /* each of these channels may be sitting behind a channel proxy (i.e. chan_agent)
2886            and if so, we don't really want to masquerade it, but its proxy */
2887         if (original->_bridge && (original->_bridge != ast_bridged_channel(original)))
2888                 final_orig = original->_bridge;
2889
2890         if (clone->_bridge && (clone->_bridge != ast_bridged_channel(clone)))
2891                 final_clone = clone->_bridge;
2892
2893         if ((final_orig != original) || (final_clone != clone)) {
2894                 ast_channel_lock(final_orig);
2895                 while (ast_channel_trylock(final_clone)) {
2896                         ast_channel_unlock(final_orig);
2897                         usleep(1);
2898                         ast_channel_lock(final_orig);
2899                 }
2900                 ast_channel_unlock(clone);
2901                 ast_channel_unlock(original);
2902                 original = final_orig;
2903                 clone = final_clone;
2904         }
2905
2906         if (original == clone) {
2907                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2908                 ast_channel_unlock(clone);
2909                 ast_channel_unlock(original);
2910                 return -1;
2911         }
2912
2913         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2914                 clone->name, original->name);
2915         if (original->masq) {
2916                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2917                         original->masq->name, original->name);
2918         } else if (clone->masqr) {
2919                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n",
2920                         clone->name, clone->masqr->name);
2921         } else {
2922                 original->masq = clone;
2923                 clone->masqr = original;
2924                 ast_queue_frame(original, &ast_null_frame);
2925                 ast_queue_frame(clone, &ast_null_frame);
2926                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2927                 res = 0;
2928         }
2929
2930         ast_channel_unlock(clone);
2931         ast_channel_unlock(original);
2932
2933         return res;
2934 }
2935
2936 void ast_change_name(struct ast_channel *chan, char *newname)
2937 {
2938         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", chan->name, newname, chan->uniqueid);
2939         ast_string_field_set(chan, name, newname);
2940 }
2941
2942 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2943 {
2944         struct ast_var_t *current, *newvar;
2945         const char *varname;
2946
2947         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2948                 int vartype = 0;
2949
2950                 varname = ast_var_full_name(current);
2951                 if (!varname)
2952                         continue;
2953
2954                 if (varname[0] == '_') {
2955                         vartype = 1;
2956                         if (varname[1] == '_')
2957                                 vartype = 2;
2958                 }
2959
2960                 switch (vartype) {
2961                 case 1:
2962                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2963                         if (newvar) {
2964                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2965                                 if (option_debug)
2966                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2967                         }
2968                         break;
2969                 case 2:
2970                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2971                         if (newvar) {
2972                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2973                                 if (option_debug)
2974                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2975                         }
2976                         break;
2977                 default:
2978                         if (option_debug)
2979                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2980                         break;
2981                 }
2982         }
2983 }
2984
2985 /*!
2986   \brief Clone channel variables from 'clone' channel into 'original' channel
2987
2988   All variables except those related to app_groupcount are cloned.
2989   Variables are actually _removed_ from 'clone' channel, presumably
2990   because it will subsequently be destroyed.
2991
2992   \note Assumes locks will be in place on both channels when called.
2993 */
2994 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2995 {
2996         struct ast_var_t *varptr;
2997
2998         /* we need to remove all app_groupcount related variables from the original
2999            channel before merging in the clone's variables; any groups assigned to the
3000            original channel should be released, only those assigned to the clone
3001            should remain
3002         */
3003
3004         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
3005                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
3006                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
3007                         ast_var_delete(varptr);
3008                 }
3009         }
3010         AST_LIST_TRAVERSE_SAFE_END;
3011
3012         /* Append variables from clone channel into original channel */
3013         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
3014         if (AST_LIST_FIRST(&clone->varshead))
3015                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
3016 }
3017
3018 /*!
3019   \brief Masquerade a channel
3020
3021   \note Assumes channel will be locked when called
3022 */
3023 int ast_do_masquerade(struct ast_channel *original)
3024 {
3025         int x,i;
3026         int res=0;
3027         int origstate;
3028         struct ast_frame *cur, *prev;
3029         const struct ast_channel_tech *t;
3030         void *t_pvt;
3031         struct ast_callerid tmpcid;
3032         struct ast_channel *clone = original->masq;
3033         int rformat = original->readformat;
3034         int wformat = original->writeformat;
3035         char newn[100];
3036         char orig[100];
3037         char masqn[100];
3038         char zombn[100];
3039
3040         if (option_debug > 3)
3041                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
3042                         clone->name, clone->_state, original->name, original->_state);
3043
3044         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
3045            the clone channel into the original channel.  Start by killing off the original
3046            channel's backend.   I'm not sure we're going to keep this function, because
3047            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
3048
3049         /* We need the clone's lock, too */
3050         ast_channel_lock(clone);
3051
3052         if (option_debug > 1)
3053                 ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
3054
3055         /* Having remembered the original read/write formats, we turn off any translation on either
3056            one */
3057         free_translation(clone);
3058         free_translation(original);
3059
3060
3061         /* Unlink the masquerade */
3062         original->masq = NULL;
3063         clone->masqr = NULL;
3064         
3065         /* Save the original name */
3066         ast_copy_string(orig, original->name, sizeof(orig));
3067         /* Save the new name */
3068         ast_copy_string(newn, clone->name, sizeof(newn));
3069         /* Create the masq name */
3070         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
3071                 
3072         /* Copy the name from the clone channel */
3073         ast_string_field_set(original, name, newn);
3074
3075         /* Mangle the name of the clone channel */
3076         ast_string_field_set(clone, name, masqn);
3077         
3078         /* Notify any managers of the change, first the masq then the other */
3079         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
3080         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
3081
3082         /* Swap the technologies */     
3083         t = original->tech;
3084         original->tech = clone->tech;
3085         clone->tech = t;
3086
3087         t_pvt = original->tech_pvt;
3088         original->tech_pvt = clone->tech_pvt;
3089         clone->tech_pvt = t_pvt;
3090
3091         /* Swap the readq's */
3092         cur = original->readq;
3093         original->readq = clone->readq;
3094         clone->readq = cur;
3095
3096         /* Swap the alertpipes */
3097         for (i = 0; i < 2; i++) {
3098                 x = original->alertpipe[i];
3099                 original->alertpipe[i] = clone->alertpipe[i];
3100                 clone->alertpipe[i] = x;
3101         }
3102
3103         /* Swap the raw formats */
3104         x = original->rawreadformat;
3105         original->rawreadformat = clone->rawreadformat;
3106         clone->rawreadformat = x;
3107         x = original->rawwriteformat;
3108         original->rawwriteformat = clone->rawwriteformat;
3109         clone->rawwriteformat = x;
3110
3111         /* Save any pending frames on both sides.  Start by counting
3112          * how many we're going to need... */
3113         prev = NULL;
3114         x = 0;
3115         for (cur = clone->readq; cur; cur = cur->next) {
3116                 x++;
3117                 prev = cur;
3118         }
3119         /* If we had any, prepend them to the ones already in the queue, and
3120          * load up the alertpipe */
3121         if (prev) {
3122                 prev->next = original->readq;
3123                 original->readq = clone->readq;
3124                 clone->readq = NULL;
3125                 if (original->alertpipe[1] > -1) {
3126                         for (i = 0; i < x; i++)
3127                                 write(original->alertpipe[1], &x, sizeof(x));
3128                 }
3129         }
3130         clone->_softhangup = AST_SOFTHANGUP_DEV;
3131
3132
3133         /* And of course, so does our current state.  Note we need not
3134            call ast_setstate since the event manager doesn't really consider
3135            these separate.  We do this early so that the clone has the proper
3136            state of the original channel. */
3137         origstate = original->_state;
3138         original->_state = clone->_state;
3139         clone->_state = origstate;
3140
3141         if (clone->tech->fixup){
3142                 res = clone->tech->fixup(original, clone);
3143                 if (res)
3144                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3145         }
3146
3147         /* Start by disconnecting the original's physical side */
3148         if (clone->tech->hangup)
3149                 res = clone->tech->hangup(clone);
3150         if (res) {
3151                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3152                 ast_channel_unlock(clone);
3153                 return -1;
3154         }
3155         
3156         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3157         /* Mangle the name of the clone channel */
3158         ast_string_field_set(clone, name, zombn);
3159         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3160
3161         /* Update the type. */
3162         t_pvt = original->monitor;
3163         original->monitor = clone->monitor;
3164         clone->monitor = t_pvt;
3165         
3166         /* Keep the same language.  */
3167         ast_string_field_set(original, language, clone->language);
3168         /* Copy the FD's other than the generator fd */
3169         for (x = 0; x < AST_MAX_FDS; x++) {
3170                 if (x != AST_GENERATOR_FD)
3171                         original->fds[x] = clone->fds[x];
3172         }
3173         /* Move data stores over */
3174         if (AST_LIST_FIRST(&clone->datastores))
3175                 AST_LIST_INSERT_TAIL(&original->datastores, AST_LIST_FIRST(&clone->datastores), entry);
3176         AST_LIST_HEAD_INIT_NOLOCK(&clone->datastores);
3177
3178         clone_variables(original, clone);
3179         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3180         /* Presense of ADSI capable CPE follows clone */
3181         original->adsicpe = clone->adsicpe;
3182         /* Bridge remains the same */
3183         /* CDR fields remain the same */
3184         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3185         /* Application and data remain the same */
3186         /* Clone exception  becomes real one, as with fdno */
3187         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3188         original->fdno = clone->fdno;
3189         /* Schedule context remains the same */
3190         /* Stream stuff stays the same */
3191         /* Keep the original state.  The fixup code will need to work with it most likely */
3192
3193         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3194            out. */
3195         tmpcid = original->cid;
3196         original->cid = clone->cid;
3197         clone->cid = tmpcid;
3198         
3199         /* Restore original timing file descriptor */
3200         original->fds[AST_TIMING_FD] = original->timingfd;
3201         
3202         /* Our native formats are different now */
3203         original->nativeformats = clone->nativeformats;
3204         
3205         /* Context, extension, priority, app data, jump table,  remain the same */
3206         /* pvt switches.  pbx stays the same, as does next */
3207         
3208         /* Set the write format */
3209         ast_set_write_format(original, wformat);
3210
3211         /* Set the read format */
3212         ast_set_read_format(original, rformat);
3213
3214         /* Copy the music class */
3215         ast_string_field_set(original, musicclass, clone->musicclass);
3216
3217         if (option_debug)
3218                 ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3219
3220         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3221            can fix up everything as best as possible */
3222         if (original->tech->fixup) {
3223                 res = original->tech->fixup(clone, original);
3224                 if (res) {
3225                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3226                                 original->tech->type, original->name);
3227                         ast_channel_unlock(clone);
3228                         return -1;
3229                 }
3230         } else
3231                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3232                         original->tech->type, original->name);
3233         
3234         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
3235            a zombie so nothing tries to touch it.  If it's already been marked as a
3236            zombie, then free it now (since it already is considered invalid). */
3237         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3238                 if (option_debug)
3239                         ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3240                 ast_channel_unlock(clone);
3241                 manager_event(EVENT_FLAG_CALL, "Hangup",
3242                         "Channel: %s\r\n"
3243                         "Uniqueid: %s\r\n"
3244                         "Cause: %d\r\n"
3245                         "Cause-txt: %s\r\n",
3246                         clone->name,
3247                         clone->uniqueid,
3248                         clone->hangupcause,
3249                         ast_cause2str(clone->hangupcause)
3250                         );
3251                 ast_channel_free(clone);
3252         } else {
3253                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3254                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3255                 ast_queue_frame(clone, &ast_null_frame);
3256                 ast_channel_unlock(clone);
3257         }
3258         
3259         /* Signal any blocker */
3260         if (ast_test_flag(original, AST_FLAG_BLOCKING))
3261                 pthread_kill(original->blocker, SIGURG);
3262         if (option_debug)
3263                 ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3264         return 0;
3265 }
3266
3267 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3268 {
3269         if (callerid) {
3270                 if (chan->cid.cid_num)
3271                         free(chan->cid.cid_num);
3272                 chan->cid.cid_num = ast_strdup(callerid);
3273         }
3274         if (calleridname) {
3275                 if (chan->cid.cid_name)
3276                         free(chan->cid.cid_name);
3277                 chan->cid.cid_name = ast_strdup(calleridname);
3278         }
3279         if (ani) {
3280                 if (chan->cid.cid_ani)
3281                         free(chan->cid.cid_ani);
3282                 chan->cid.cid_ani = ast_strdup(ani);
3283         }
3284         if (chan->cdr)
3285                 ast_cdr_setcid(chan->cdr, chan);
3286         manager_event(EVENT_FLAG_CALL, "Newcallerid",
3287                                 "Channel: %s\r\n"
3288                                 "CallerID: %s\r\n"
3289                                 "CallerIDName: %s\r\n"
3290                                 "Uniqueid: %s\r\n"
3291                                 "CID-CallingPres: %d (%s)\r\n",
3292                                 chan->name,
3293                                 S_OR(chan->cid.cid_num, "<Unknown>"),
3294                                 S_OR(chan->cid.cid_name, "<Unknown>"),
3295                                 chan->uniqueid,
3296                                 chan->cid.cid_pres,
3297                                 ast_describe_caller_presentation(chan->cid.cid_pres)
3298                                 );
3299 }
3300
3301 int ast_setstate(struct ast_channel *chan, int state)
3302 {
3303         int oldstate = chan->_state;
3304
3305         if (oldstate == state)
3306                 return 0;
3307
3308         chan->_state = state;
3309         ast_device_state_changed_literal(chan->name);
3310         manager_event(EVENT_FLAG_CALL,
3311                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3312                       "Channel: %s\r\n"
3313                       "State: %s\r\n"
3314                       "CallerID: %s\r\n"
3315                       "CallerIDName: %s\r\n"
3316                       "Uniqueid: %s\r\n",
3317                       chan->name, ast_state2str(chan->_state),
3318                       S_OR(chan->cid.cid_num, "<unknown>"),
3319                       S_OR(chan->cid.cid_name, "<unknown>"),
3320                       chan->uniqueid);
3321
3322         return 0;
3323 }
3324
3325 /*! \brief Find bridged channel */
3326 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3327 {
3328         struct ast_channel *bridged;
3329         bridged = chan->_bridge;
3330         if (bridged && bridged->tech->bridged_channel)
3331                 bridged = bridged->tech->bridged_channel(chan, bridged);
3332         return bridged;
3333 }
3334
3335 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain)
3336 {
3337         int min = 0, sec = 0, check;
3338
3339         check = ast_autoservice_start(peer);
3340         if (check)
3341                 return;
3342
3343         if (remain > 0) {
3344                 if (remain / 60 > 1) {
3345                         min = remain / 60;
3346                         sec = remain % 60;
3347                 } else {
3348                         sec = remain;
3349                 }
3350         }
3351         
3352         if (!strcmp(sound,"timeleft")) {        /* Queue support */
3353                 ast_stream_and_wait(chan, "vm-youhave", chan->language, "");
3354                 if (min) {
3355                         ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, NULL);
3356                         ast_stream_and_wait(chan, "queue-minutes", chan->language, "");
3357                 }
3358                 if (sec) {
3359                         ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, NULL);
3360                         ast_stream_and_wait(chan, "queue-seconds", chan->language, "");
3361                 }
3362         } else {
3363                 ast_stream_and_wait(chan, sound, chan->language, "");
3364         }
3365
3366         ast_autoservice_stop(peer);
3367 }
3368
3369 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3370                                                  struct ast_bridge_config *config, struct ast_frame **fo,
3371                                                  struct ast_channel **rc, struct timeval bridge_end)
3372 {
3373         /* Copy voice back and forth between the two channels. */
3374         struct ast_channel *cs[3];
3375         struct ast_frame *f;
3376         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3377         int o0nativeformats;
3378         int o1nativeformats;
3379         int watch_c0_dtmf;
3380         int watch_c1_dtmf;
3381         void *pvt0, *pvt1;
3382         /* Indicates whether a frame was queued into a jitterbuffer */
3383         int frame_put_in_jb = 0;
3384         int jb_in_use;
3385         int to;
3386         
3387         cs[0] = c0;
3388         cs[1] = c1;
3389         pvt0 = c0->tech_pvt;
3390         pvt1 = c1->tech_pvt;
3391         o0nativeformats = c0->nativeformats;
3392         o1nativeformats = c1->nativeformats;
3393         watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3394         watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3395
3396         /* Check the need of a jitterbuffer for each channel */
3397         jb_in_use = ast_jb_do_usecheck(c0, c1);
3398
3399         for (;;) {
3400                 struct ast_channel *who, *other;
3401
3402                 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3403                     (o0nativeformats != c0->nativeformats) ||
3404                     (o1nativeformats != c1->nativeformats)) {
3405                         /* Check for Masquerade, codec changes, etc */
3406                         res = AST_BRIDGE_RETRY;
3407                         break;
3408                 }
3409                 if (bridge_end.tv_sec) {
3410                         to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3411                         if (to <= 0) {
3412                                 res = AST_BRIDGE_RETRY;
3413                                 break;
3414                         }
3415                 } else
3416                         to = -1;
3417                 /* Calculate the appropriate max sleep interval - in general, this is the time,
3418                    left to the closest jb delivery moment */
3419                 if (jb_in_use)
3420                         to = ast_jb_get_when_to_wakeup(c0, c1, to);
3421                 who = ast_waitfor_n(cs, 2, &to);
3422                 if (!who) {
3423                         /* No frame received within the specified timeout - check if we have to deliver now */
3424                         if (jb_in_use)
3425                                 ast_jb_get_and_deliver(c0, c1);
3426                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3427                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3428                                         c0->_softhangup = 0;
3429                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3430                                         c1->_softhangup = 0;
3431                                 c0->_bridge = c1;
3432                                 c1->_bridge = c0;
3433                         }
3434                         continue;
3435                 }
3436                 f = ast_read(who);
3437                 if (!f) {
3438                         *fo = NULL;
3439                         *rc = who;
3440                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3441                         break;
3442                 }
3443
3444                 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3445                 /* Try add the frame info the who's bridged channel jitterbuff */
3446                 if (jb_in_use)
3447                         frame_put_in_jb = !ast_jb_put(other, f);
3448
3449                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3450                         int bridge_exit = 0;
3451
3452                         switch (f->subclass) {
3453                         case AST_CONTROL_HOLD:
3454                         case AST_CONTROL_UNHOLD:
3455                         case AST_CONTROL_VIDUPDATE:
3456                                 ast_indicate_data(other, f->subclass, f->data, f->datalen);
3457                                 break;
3458                         default:
3459                                 *fo = f;
3460                                 *rc = who;
3461                                 bridge_exit = 1;
3462                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3463                                 break;
3464                         }
3465                         if (bridge_exit)
3466                                 break;
3467                 }
3468                 if ((f->frametype == AST_FRAME_VOICE) ||
3469                     (f->frametype == AST_FRAME_DTMF) ||
3470                     (f->frametype == AST_FRAME_VIDEO) ||
3471                     (f->frametype == AST_FRAME_IMAGE) ||
3472                     (f->frametype == AST_FRAME_HTML) ||
3473                     (f->frametype == AST_FRAME_MODEM) ||
3474                     (f->frametype == AST_FRAME_TEXT)) {
3475                         /* monitored dtmf causes exit from bridge */
3476                         int monitored_source = (who == c0) ? watch_c0_dtmf : watch_c1_dtmf;
3477
3478                         if (f->frametype == AST_FRAME_DTMF && monitored_source) {
3479                                 *fo = f;
3480                                 *rc = who;
3481                                 ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3482                                 break;
3483                         }
3484                         /* Write immediately frames, not passed through jb */
3485                         if (!frame_put_in_jb)
3486                                 ast_write(other, f);
3487                                 
3488                         /* Check if we have to deliver now */
3489                         if (jb_in_use)
3490                                 ast_jb_get_and_deliver(c0, c1);
3491                 }
3492                 /* XXX do we want to pass on also frames not matched above ? */
3493                 ast_frfree(f);
3494
3495                 /* Swap who gets priority */
3496                 cs[2] = cs[0];
3497                 cs[0] = cs[1];
3498                 cs[1] = cs[2];
3499         }
3500         return res;
3501 }
3502
3503 /*! \brief Bridge two channels together */
3504 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3505                                           struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc)
3506 {
3507         struct ast_channel *who = NULL;
3508         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3509         int nativefailed=0;
3510         int firstpass;
3511         int o0nativeformats;
3512         int o1nativeformats;
3513         long time_left_ms=0;
3514         struct timeval nexteventts = { 0, };
3515         char caller_warning = 0;
3516         char callee_warning = 0;
3517         int to;
3518
3519         if (c0->_bridge) {
3520                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3521                         c0->name, c0->_bridge->name);
3522                 return -1;
3523         }
3524         if (c1->_bridge) {
3525                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n",
3526                         c1->name, c1->_bridge->name);
3527                 return -1;
3528         }
3529         
3530         /* Stop if we're a zombie or need a soft hangup */
3531         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3532             ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1))
3533                 return -1;
3534
3535         *fo = NULL;
3536         firstpass = config->firstpass;
3537         config->firstpass = 0;
3538
3539         if (ast_tvzero(config->start_time))
3540                 config->start_time = ast_tvnow();
3541         time_left_ms = config->timelimit;
3542
3543         caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3544         callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3545
3546         if (config->start_sound && firstpass) {
3547                 if (caller_warning)
3548                         bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3549                 if (callee_warning)
3550                         bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3551         }
3552
3553         /* Keep track of bridge */
3554         c0->_bridge = c1;
3555         c1->_bridge = c0;
3556
3557         /* \todo  XXX here should check that cid_num is not NULL */
3558         manager_event(EVENT_FLAG_CALL, "Link",
3559                       "Channel1: %s\r\n"
3560                       "Channel2: %s\r\n"
3561                       "Uniqueid1: %s\r\n"
3562                       "Uniqueid2: %s\r\n"
3563                       "CallerID1: %s\r\n"
3564                       "CallerID2: %s\r\n",
3565                       c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3566
3567         o0nativeformats = c0->nativeformats;
3568         o1nativeformats = c1->nativeformats;
3569
3570         if (config->timelimit) {
3571                 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3572                 if (caller_warning || callee_warning)
3573                         nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3574         }
3575
3576         for (/* ever */;;) {
3577                 to = -1;
3578                 if (config->timelimit) {
3579                         struct timeval now;
3580                         now = ast_tvnow();
3581                         to = ast_tvdiff_ms(nexteventts, now);
3582                         if (to < 0)
3583                                 to = 0;
3584                         time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3585                         if (time_left_ms < to)
3586                                 to = time_left_ms;
3587
3588                         if (time_left_ms <= 0) {
3589                                 if (caller_warning && config->end_sound)
3590                                         bridge_playfile(c0, c1, config->end_sound, 0);
3591                                 if (callee_warning && config->end_sound)
3592                                         bridge_playfile(c1, c0, config->end_sound, 0);
3593                                 *fo = NULL;
3594                                 if (who)
3595                                         *rc = who;
3596                                 res = 0;
3597                                 break;
3598                         }
3599                         
3600                         if (!to) {
3601                                 if (time_left_ms >= 5000 && config->warning_sound && config->play_warning) {
3602                                         int t = (time_left_ms + 500) / 1000; /* round to nearest second */
3603                                         if (caller_warning)
3604                                                 bridge_playfile(c0, c1, config->warning_sound, t);
3605                                         if (callee_warning)
3606                                                 bridge_playfile(c1, c0, config->warning_sound, t);
3607                                 }
3608                                 if (config->warning_freq) {
3609                                         nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3610                                 } else
3611                                         nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3612                         }
3613                 }
3614
3615                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3616                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3617                                 c0->_softhangup = 0;
3618                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3619                                 c1->_softhangup = 0;
3620                         c0->_bridge = c1;
3621                         c1->_bridge = c0;
3622                         ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3623                         continue;
3624                 }
3625