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