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