3db38b6cc1059ae5e88a47b244a126eca641e416
[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                 f->next = NULL;
1908                 /* Interpret hangup and return NULL */
1909                 if ((f->frametype == AST_FRAME_CONTROL) && (f->subclass == AST_CONTROL_HANGUP)) {
1910                         ast_frfree(f);
1911                         f = NULL;
1912                 }
1913         } else {
1914                 chan->blocker = pthread_self();
1915                 if (ast_test_flag(chan, AST_FLAG_EXCEPTION)) {
1916                         if (chan->tech->exception) 
1917                                 f = chan->tech->exception(chan);
1918                         else {
1919                                 ast_log(LOG_WARNING, "Exception flag set on '%s', but no exception handler\n", chan->name);
1920                                 f = &null_frame;
1921                         }
1922                         /* Clear the exception flag */
1923                         ast_clear_flag(chan, AST_FLAG_EXCEPTION);
1924                 } else {
1925                         if (chan->tech->read)
1926                                 f = chan->tech->read(chan);
1927                         else
1928                                 ast_log(LOG_WARNING, "No read routine on channel %s\n", chan->name);
1929                 }
1930         }
1931
1932         if (f) {
1933                 /* if the channel driver returned more than one frame, stuff the excess
1934                    into the readq for the next ast_read call
1935                 */
1936                 if (f->next) {
1937                         chan->readq = f->next;
1938                         f->next = NULL;
1939                 }
1940
1941                 switch (f->frametype) {
1942                 case AST_FRAME_CONTROL:
1943                         if (f->subclass == AST_CONTROL_ANSWER) {
1944                                 if (prestate == AST_STATE_UP) {
1945                                         ast_log(LOG_DEBUG, "Dropping duplicate answer!\n");
1946                                         f = &null_frame;
1947                                 }
1948                                 /* Answer the CDR */
1949                                 ast_setstate(chan, AST_STATE_UP);
1950                                 ast_cdr_answer(chan->cdr);
1951                         }
1952                         break;
1953                 case AST_FRAME_DTMF:
1954                         ast_log(LOG_DTMF, "DTMF '%c' received on %s\n", f->subclass, chan->name);
1955                         if (ast_test_flag(chan, AST_FLAG_DEFER_DTMF)) {
1956                                 if (strlen(chan->dtmfq) < sizeof(chan->dtmfq) - 2)
1957                                         chan->dtmfq[strlen(chan->dtmfq)] = f->subclass;
1958                                 else
1959                                         ast_log(LOG_WARNING, "Dropping deferred DTMF digits on %s\n", chan->name);
1960                                 f = &null_frame;
1961                         }
1962                         break;
1963                 case AST_FRAME_DTMF_BEGIN:
1964                         ast_log(LOG_DTMF, "DTMF begin '%c' received on %s\n", f->subclass, chan->name);
1965                         break;
1966                 case AST_FRAME_DTMF_END:
1967                         ast_log(LOG_DTMF, "DTMF end '%c' received on %s\n", f->subclass, chan->name);
1968                         break;
1969                 case AST_FRAME_VOICE:
1970                         if (dropaudio) {
1971                                 ast_frfree(f);
1972                                 f = &null_frame;
1973                         } else if (!(f->subclass & chan->nativeformats)) {
1974                                 /* This frame can't be from the current native formats -- drop it on the
1975                                    floor */
1976                                 ast_log(LOG_NOTICE, "Dropping incompatible voice frame on %s of format %s since our native format has changed to %s\n",
1977                                         chan->name, ast_getformatname(f->subclass), ast_getformatname(chan->nativeformats));
1978                                 ast_frfree(f);
1979                                 f = &null_frame;
1980                         } else {
1981                                 if (chan->spies)
1982                                         queue_frame_to_spies(chan, f, SPY_READ);
1983                                 
1984                                 if (chan->monitor && chan->monitor->read_stream ) {
1985 #ifndef MONITOR_CONSTANT_DELAY
1986                                         int jump = chan->outsmpl - chan->insmpl - 4 * f->samples;
1987                                         if (jump >= 0) {
1988                                                 if (ast_seekstream(chan->monitor->read_stream, jump + f->samples, SEEK_FORCECUR) == -1)
1989                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1990                                                 chan->insmpl += jump + 4 * f->samples;
1991                                         } else
1992                                                 chan->insmpl+= f->samples;
1993 #else
1994                                         int jump = chan->outsmpl - chan->insmpl;
1995                                         if (jump - MONITOR_DELAY >= 0) {
1996                                                 if (ast_seekstream(chan->monitor->read_stream, jump - f->samples, SEEK_FORCECUR) == -1)
1997                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring read stream, synchronization between the files may be broken\n");
1998                                                 chan->insmpl += jump;
1999                                         } else
2000                                                 chan->insmpl += f->samples;
2001 #endif
2002                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2003                                                 if (ast_writestream(chan->monitor->read_stream, f) < 0)
2004                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor read stream\n");
2005                                         }
2006                                 }
2007
2008                                 if (chan->readtrans) {
2009                                         if (!(f = ast_translate(chan->readtrans, f, 1)))
2010                                                 f = &null_frame;
2011                                 }
2012
2013                                 /* Run any generator sitting on the channel */
2014                                 if (chan->generatordata) {
2015                                         /* Mask generator data temporarily and apply.  If there is a timing function, it
2016                                            will be calling the generator instead */
2017                                         void *tmp;
2018                                         int res;
2019                                         int (*generate)(struct ast_channel *chan, void *tmp, int datalen, int samples);
2020                                         
2021                                         if (chan->timingfunc) {
2022                                                 ast_log(LOG_DEBUG, "Generator got voice, switching to phase locked mode\n");
2023                                                 ast_settimeout(chan, 0, NULL, NULL);
2024                                         }
2025                                         tmp = chan->generatordata;
2026                                         chan->generatordata = NULL;
2027                                         generate = chan->generator->generate;
2028                                         res = generate(chan, tmp, f->datalen, f->samples);
2029                                         chan->generatordata = tmp;
2030                                         if (res) {
2031                                                 ast_log(LOG_DEBUG, "Auto-deactivating generator\n");
2032                                                 ast_deactivate_generator(chan);
2033                                         }
2034                                 } else if (f->frametype == AST_FRAME_CNG) {
2035                                         if (chan->generator && !chan->timingfunc && (chan->timingfd > -1)) {
2036                                                 ast_log(LOG_DEBUG, "Generator got CNG, switching to timed mode\n");
2037                                                 ast_settimeout(chan, 160, generator_force, chan);
2038                                         }
2039                                 }
2040                         }
2041                 }
2042         } else {
2043                 /* Make sure we always return NULL in the future */
2044                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2045                 if (chan->generator)
2046                         ast_deactivate_generator(chan);
2047                 /* End the CDR if appropriate */
2048                 if (chan->cdr)
2049                         ast_cdr_end(chan->cdr);
2050         }
2051
2052         /* High bit prints debugging */
2053         if (chan->fin & 0x80000000)
2054                 ast_frame_dump(chan->name, f, "<<");
2055         if ((chan->fin & 0x7fffffff) == 0x7fffffff)
2056                 chan->fin &= 0x80000000;
2057         else
2058                 chan->fin++;
2059         ast_mutex_unlock(&chan->lock);
2060
2061         return f;
2062 }
2063
2064 struct ast_frame *ast_read(struct ast_channel *chan)
2065 {
2066         return __ast_read(chan, 0);
2067 }
2068
2069 struct ast_frame *ast_read_noaudio(struct ast_channel *chan)
2070 {
2071         return __ast_read(chan, 1);
2072 }
2073
2074 int ast_indicate(struct ast_channel *chan, int condition)
2075 {
2076         int res = -1;
2077
2078         ast_mutex_lock(&chan->lock);
2079         /* Stop if we're a zombie or need a soft hangup */
2080         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) {
2081                 ast_mutex_unlock(&chan->lock);
2082                 return -1;
2083         }
2084         if (chan->tech->indicate)
2085                 res = chan->tech->indicate(chan, condition);
2086         ast_mutex_unlock(&chan->lock);
2087         if (!chan->tech->indicate || res) {
2088                 /*
2089                  * Device does not support (that) indication, lets fake
2090                  * it by doing our own tone generation. (PM2002)
2091                  */
2092                 if (condition >= 0) {
2093                         const struct tone_zone_sound *ts = NULL;
2094                         switch (condition) {
2095                         case AST_CONTROL_RINGING:
2096                                 ts = ast_get_indication_tone(chan->zone, "ring");
2097                                 break;
2098                         case AST_CONTROL_BUSY:
2099                                 ts = ast_get_indication_tone(chan->zone, "busy");
2100                                 break;
2101                         case AST_CONTROL_CONGESTION:
2102                                 ts = ast_get_indication_tone(chan->zone, "congestion");
2103                                 break;
2104                         }
2105                         if (ts && ts->data[0]) {
2106                                 ast_log(LOG_DEBUG, "Driver for channel '%s' does not support indication %d, emulating it\n", chan->name, condition);
2107                                 ast_playtones_start(chan,0,ts->data, 1);
2108                                 res = 0;
2109                         } else if (condition == AST_CONTROL_PROGRESS) {
2110                                 /* ast_playtones_stop(chan); */
2111                         } else if (condition == AST_CONTROL_PROCEEDING) {
2112                                 /* Do nothing, really */
2113                         } else if (condition == AST_CONTROL_HOLD) {
2114                                 /* Do nothing.... */
2115                         } else if (condition == AST_CONTROL_UNHOLD) {
2116                                 /* Do nothing.... */
2117                         } else if (condition == AST_CONTROL_VIDUPDATE) {
2118                                 /* Do nothing.... */
2119                         } else {
2120                                 /* not handled */
2121                                 ast_log(LOG_WARNING, "Unable to handle indication %d for '%s'\n", condition, chan->name);
2122                                 res = -1;
2123                         }
2124                 }
2125                 else ast_playtones_stop(chan);
2126         }
2127         return res;
2128 }
2129
2130 int ast_recvchar(struct ast_channel *chan, int timeout)
2131 {
2132         int c;
2133         char *buf = ast_recvtext(chan, timeout);
2134         if (buf == NULL)
2135                 return -1;      /* error or timeout */
2136         c = *(unsigned char *)buf;
2137         free(buf);
2138         return c;
2139 }
2140
2141 char *ast_recvtext(struct ast_channel *chan, int timeout)
2142 {
2143         int res, done = 0;
2144         char *buf = NULL;
2145         
2146         while (!done) {
2147                 struct ast_frame *f;
2148                 if (ast_check_hangup(chan))
2149                         break;
2150                 res = ast_waitfor(chan, timeout);
2151                 if (res <= 0) /* timeout or error */
2152                         break;
2153                 timeout = res;  /* update timeout */
2154                 f = ast_read(chan);
2155                 if (f == NULL)
2156                         break; /* no frame */
2157                 if (f->frametype == AST_FRAME_CONTROL && f->subclass == AST_CONTROL_HANGUP)
2158                         done = 1;       /* force a break */
2159                 else if (f->frametype == AST_FRAME_TEXT) {              /* what we want */
2160                         buf = strndup((char *) f->data, f->datalen);    /* dup and break */
2161                         done = 1;
2162                 }
2163                 ast_frfree(f);
2164         }
2165         return buf;
2166 }
2167
2168 int ast_sendtext(struct ast_channel *chan, const char *text)
2169 {
2170         int res = 0;
2171         /* Stop if we're a zombie or need a soft hangup */
2172         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan)) 
2173                 return -1;
2174         CHECK_BLOCKING(chan);
2175         if (chan->tech->send_text)
2176                 res = chan->tech->send_text(chan, text);
2177         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2178         return res;
2179 }
2180
2181 static int do_senddigit(struct ast_channel *chan, char digit)
2182 {
2183         int res = -1;
2184
2185         if (chan->tech->send_digit)
2186                 res = chan->tech->send_digit(chan, digit);
2187         if (!chan->tech->send_digit || res) {
2188                 /*
2189                  * Device does not support DTMF tones, lets fake
2190                  * it by doing our own generation. (PM2002)
2191                  */
2192                 static const char* dtmf_tones[] = {
2193                         "!941+1336/100,!0/100", /* 0 */
2194                         "!697+1209/100,!0/100", /* 1 */
2195                         "!697+1336/100,!0/100", /* 2 */
2196                         "!697+1477/100,!0/100", /* 3 */
2197                         "!770+1209/100,!0/100", /* 4 */
2198                         "!770+1336/100,!0/100", /* 5 */
2199                         "!770+1477/100,!0/100", /* 6 */
2200                         "!852+1209/100,!0/100", /* 7 */
2201                         "!852+1336/100,!0/100", /* 8 */
2202                         "!852+1477/100,!0/100", /* 9 */
2203                         "!697+1633/100,!0/100", /* A */
2204                         "!770+1633/100,!0/100", /* B */
2205                         "!852+1633/100,!0/100", /* C */
2206                         "!941+1633/100,!0/100", /* D */
2207                         "!941+1209/100,!0/100", /* * */
2208                         "!941+1477/100,!0/100" };       /* # */
2209                 if (digit >= '0' && digit <='9')
2210                         ast_playtones_start(chan, 0, dtmf_tones[digit-'0'], 0);
2211                 else if (digit >= 'A' && digit <= 'D')
2212                         ast_playtones_start(chan, 0, dtmf_tones[digit-'A'+10], 0);
2213                 else if (digit == '*')
2214                         ast_playtones_start(chan, 0, dtmf_tones[14], 0);
2215                 else if (digit == '#')
2216                         ast_playtones_start(chan, 0, dtmf_tones[15], 0);
2217                 else {
2218                         /* not handled */
2219                         ast_log(LOG_DEBUG, "Unable to generate DTMF tone '%c' for '%s'\n", digit, chan->name);
2220                 }
2221         }
2222         return 0;
2223 }
2224
2225 int ast_senddigit(struct ast_channel *chan, char digit)
2226 {
2227         return do_senddigit(chan, digit);
2228 }
2229
2230 int ast_prod(struct ast_channel *chan)
2231 {
2232         struct ast_frame a = { AST_FRAME_VOICE };
2233         char nothing[128];
2234
2235         /* Send an empty audio frame to get things moving */
2236         if (chan->_state != AST_STATE_UP) {
2237                 ast_log(LOG_DEBUG, "Prodding channel '%s'\n", chan->name);
2238                 a.subclass = chan->rawwriteformat;
2239                 a.data = nothing + AST_FRIENDLY_OFFSET;
2240                 a.src = "ast_prod";
2241                 if (ast_write(chan, &a))
2242                         ast_log(LOG_WARNING, "Prodding channel '%s' failed\n", chan->name);
2243         }
2244         return 0;
2245 }
2246
2247 int ast_write_video(struct ast_channel *chan, struct ast_frame *fr)
2248 {
2249         int res;
2250         if (!chan->tech->write_video)
2251                 return 0;
2252         res = ast_write(chan, fr);
2253         if (!res)
2254                 res = 1;
2255         return res;
2256 }
2257
2258 int ast_write(struct ast_channel *chan, struct ast_frame *fr)
2259 {
2260         int res = -1;
2261         struct ast_frame *f = NULL;
2262         /* Stop if we're a zombie or need a soft hangup */
2263         ast_mutex_lock(&chan->lock);
2264         if (ast_test_flag(chan, AST_FLAG_ZOMBIE) || ast_check_hangup(chan))  {
2265                 ast_mutex_unlock(&chan->lock);
2266                 return -1;
2267         }
2268         /* Handle any pending masquerades */
2269         if (chan->masq) {
2270                 if (ast_do_masquerade(chan)) {
2271                         ast_log(LOG_WARNING, "Failed to perform masquerade\n");
2272                         ast_mutex_unlock(&chan->lock);
2273                         return -1;
2274                 }
2275         }
2276         if (chan->masqr) {
2277                 ast_mutex_unlock(&chan->lock);
2278                 return 0;
2279         }
2280         if (chan->generatordata) {
2281                 if (ast_test_flag(chan, AST_FLAG_WRITE_INT))
2282                         ast_deactivate_generator(chan);
2283                 else {
2284                         ast_mutex_unlock(&chan->lock);
2285                         return 0;
2286                 }
2287         }
2288         /* High bit prints debugging */
2289         if (chan->fout & 0x80000000)
2290                 ast_frame_dump(chan->name, fr, ">>");
2291         CHECK_BLOCKING(chan);
2292         switch(fr->frametype) {
2293         case AST_FRAME_CONTROL:
2294                 /* XXX Interpret control frames XXX */
2295                 ast_log(LOG_WARNING, "Don't know how to handle control frames yet\n");
2296                 break;
2297         case AST_FRAME_DTMF_BEGIN:
2298         case AST_FRAME_DTMF_END:
2299                 /* nothing to do with these yet */
2300                 res = 0;
2301                 break;
2302         case AST_FRAME_DTMF:
2303                 ast_clear_flag(chan, AST_FLAG_BLOCKING);
2304                 ast_mutex_unlock(&chan->lock);
2305                 res = do_senddigit(chan,fr->subclass);
2306                 ast_mutex_lock(&chan->lock);
2307                 CHECK_BLOCKING(chan);
2308                 break;
2309         case AST_FRAME_TEXT:
2310                 if (chan->tech->send_text)
2311                         res = chan->tech->send_text(chan, (char *) fr->data);
2312                 else
2313                         res = 0;
2314                 break;
2315         case AST_FRAME_HTML:
2316                 if (chan->tech->send_html)
2317                         res = chan->tech->send_html(chan, fr->subclass, (char *) fr->data, fr->datalen);
2318                 else
2319                         res = 0;
2320                 break;
2321         case AST_FRAME_VIDEO:
2322                 /* XXX Handle translation of video codecs one day XXX */
2323                 if (chan->tech->write_video)
2324                         res = chan->tech->write_video(chan, fr);
2325                 else
2326                         res = 0;
2327                 break;
2328         case AST_FRAME_VOICE:
2329                 if (chan->tech->write) {
2330                         /* Bypass translator if we're writing format in the raw write format.  This
2331                            allows mixing of native / non-native formats */
2332                         if (fr->subclass == chan->rawwriteformat)
2333                                 f = fr;
2334                         else
2335                                 f = (chan->writetrans) ? ast_translate(chan->writetrans, fr, 0) : fr;
2336                         if (f) {
2337                                 if (chan->spies)
2338                                         queue_frame_to_spies(chan, f, SPY_WRITE);
2339
2340                                 if (chan->monitor && chan->monitor->write_stream) {
2341 #ifndef MONITOR_CONSTANT_DELAY
2342                                         int jump = chan->insmpl - chan->outsmpl - 4 * f->samples;
2343                                         if (jump >= 0) {
2344                                                 if (ast_seekstream(chan->monitor->write_stream, jump + f->samples, SEEK_FORCECUR) == -1)
2345                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2346                                                 chan->outsmpl += jump + 4 * f->samples;
2347                                         } else
2348                                                 chan->outsmpl += f->samples;
2349 #else
2350                                         int jump = chan->insmpl - chan->outsmpl;
2351                                         if (jump - MONITOR_DELAY >= 0) {
2352                                                 if (ast_seekstream(chan->monitor->write_stream, jump - f->samples, SEEK_FORCECUR) == -1)
2353                                                         ast_log(LOG_WARNING, "Failed to perform seek in monitoring write stream, synchronization between the files may be broken\n");
2354                                                 chan->outsmpl += jump;
2355                                         } else
2356                                                 chan->outsmpl += f->samples;
2357 #endif
2358                                         if (chan->monitor->state == AST_MONITOR_RUNNING) {
2359                                                 if (ast_writestream(chan->monitor->write_stream, f) < 0)
2360                                                         ast_log(LOG_WARNING, "Failed to write data to channel monitor write stream\n");
2361                                         }
2362                                 }
2363
2364                                 res = chan->tech->write(chan, f);
2365                         } else
2366                                 res = 0;
2367                 }
2368         }
2369
2370         if (f && (f != fr))
2371                 ast_frfree(f);
2372         ast_clear_flag(chan, AST_FLAG_BLOCKING);
2373         /* Consider a write failure to force a soft hangup */
2374         if (res < 0)
2375                 chan->_softhangup |= AST_SOFTHANGUP_DEV;
2376         else {
2377                 if ((chan->fout & 0x7fffffff) == 0x7fffffff)
2378                         chan->fout &= 0x80000000;
2379                 else
2380                         chan->fout++;
2381         }
2382         ast_mutex_unlock(&chan->lock);
2383         return res;
2384 }
2385
2386 static int set_format(struct ast_channel *chan, int fmt, int *rawformat, int *format,
2387                       struct ast_trans_pvt **trans, const int direction)
2388 {
2389         int native;
2390         int res;
2391         
2392         /* Make sure we only consider audio */
2393         fmt &= AST_FORMAT_AUDIO_MASK;
2394         
2395         native = chan->nativeformats;
2396         /* Find a translation path from the native format to one of the desired formats */
2397         if (!direction)
2398                 /* reading */
2399                 res = ast_translator_best_choice(&fmt, &native);
2400         else
2401                 /* writing */
2402                 res = ast_translator_best_choice(&native, &fmt);
2403
2404         if (res < 0) {
2405                 ast_log(LOG_WARNING, "Unable to find a codec translation path from %s to %s\n",
2406                         ast_getformatname(native), ast_getformatname(fmt));
2407                 return -1;
2408         }
2409         
2410         /* Now we have a good choice for both. */
2411         ast_mutex_lock(&chan->lock);
2412         *rawformat = native;
2413         /* User perspective is fmt */
2414         *format = fmt;
2415         /* Free any read translation we have right now */
2416         if (*trans)
2417                 ast_translator_free_path(*trans);
2418         /* Build a translation path from the raw format to the desired format */
2419         if (!direction)
2420                 /* reading */
2421                 *trans = ast_translator_build_path(*format, *rawformat);
2422         else
2423                 /* writing */
2424                 *trans = ast_translator_build_path(*rawformat, *format);
2425         ast_mutex_unlock(&chan->lock);
2426         if (option_debug)
2427                 ast_log(LOG_DEBUG, "Set channel %s to %s format %s\n", chan->name,
2428                         direction ? "write" : "read", ast_getformatname(fmt));
2429         return 0;
2430 }
2431
2432 int ast_set_read_format(struct ast_channel *chan, int fmt)
2433 {
2434         return set_format(chan, fmt, &chan->rawreadformat, &chan->readformat,
2435                           &chan->readtrans, 0);
2436 }
2437
2438 int ast_set_write_format(struct ast_channel *chan, int fmt)
2439 {
2440         return set_format(chan, fmt, &chan->rawwriteformat, &chan->writeformat,
2441                           &chan->writetrans, 1);
2442 }
2443
2444 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)
2445 {
2446         int state = 0;
2447         int cause = 0;
2448         struct ast_channel *chan;
2449         struct ast_frame *f;
2450         int res = 0;
2451         
2452         chan = ast_request(type, format, data, &cause);
2453         if (chan) {
2454                 if (oh) {
2455                         if (oh->vars)   
2456                                 ast_set_variables(chan, oh->vars);
2457                         if (oh->cid_num && *oh->cid_num && oh->cid_name && *oh->cid_name)
2458                                 ast_set_callerid(chan, oh->cid_num, oh->cid_name, oh->cid_num);
2459                         if (oh->parent_channel)
2460                                 ast_channel_inherit_variables(oh->parent_channel, chan);
2461                 }
2462                 ast_set_callerid(chan, cid_num, cid_name, cid_num);
2463
2464                 if (!ast_call(chan, data, 0)) {
2465                         while(timeout && (chan->_state != AST_STATE_UP)) {
2466                                 res = ast_waitfor(chan, timeout);
2467                                 if (res < 0) {
2468                                         /* Something not cool, or timed out */
2469                                         break;
2470                                 }
2471                                 /* If done, break out */
2472                                 if (!res)
2473                                         break;
2474                                 if (timeout > -1)
2475                                         timeout = res;
2476                                 f = ast_read(chan);
2477                                 if (!f) {
2478                                         state = AST_CONTROL_HANGUP;
2479                                         res = 0;
2480                                         break;
2481                                 }
2482                                 if (f->frametype == AST_FRAME_CONTROL) {
2483                                         if (f->subclass == AST_CONTROL_RINGING)
2484                                                 state = AST_CONTROL_RINGING;
2485                                         else if ((f->subclass == AST_CONTROL_BUSY) || (f->subclass == AST_CONTROL_CONGESTION)) {
2486                                                 state = f->subclass;
2487                                                 ast_frfree(f);
2488                                                 break;
2489                                         } else if (f->subclass == AST_CONTROL_ANSWER) {
2490                                                 state = f->subclass;
2491                                                 ast_frfree(f);
2492                                                 break;
2493                                         } else if (f->subclass == AST_CONTROL_PROGRESS) {
2494                                                 /* Ignore */
2495                                         } else if (f->subclass == -1) {
2496                                                 /* Ignore -- just stopping indications */
2497                                         } else {
2498                                                 ast_log(LOG_NOTICE, "Don't know what to do with control frame %d\n", f->subclass);
2499                                         }
2500                                 }
2501                                 ast_frfree(f);
2502                         }
2503                 } else
2504                         ast_log(LOG_NOTICE, "Unable to call channel %s/%s\n", type, (char *)data);
2505         } else {
2506                 ast_log(LOG_NOTICE, "Unable to request channel %s/%s\n", type, (char *)data);
2507                 switch(cause) {
2508                 case AST_CAUSE_BUSY:
2509                         state = AST_CONTROL_BUSY;
2510                         break;
2511                 case AST_CAUSE_CONGESTION:
2512                         state = AST_CONTROL_CONGESTION;
2513                         break;
2514                 }
2515         }
2516         if (chan) {
2517                 /* Final fixups */
2518                 if (oh) {
2519                         if (oh->context && *oh->context)
2520                                 ast_copy_string(chan->context, oh->context, sizeof(chan->context));
2521                         if (oh->exten && *oh->exten)
2522                                 ast_copy_string(chan->exten, oh->exten, sizeof(chan->exten));
2523                         if (oh->priority)       
2524                                 chan->priority = oh->priority;
2525                 }
2526                 if (chan->_state == AST_STATE_UP) 
2527                         state = AST_CONTROL_ANSWER;
2528         }
2529         if (outstate)
2530                 *outstate = state;
2531         if (chan && res <= 0) {
2532                 if (!chan->cdr) {
2533                         chan->cdr = ast_cdr_alloc();
2534                         if (chan->cdr)
2535                                 ast_cdr_init(chan->cdr, chan);
2536                 }
2537                 if (chan->cdr) {
2538                         char tmp[256];
2539                         snprintf(tmp, 256, "%s/%s", type, (char *)data);
2540                         ast_cdr_setapp(chan->cdr,"Dial",tmp);
2541                         ast_cdr_update(chan);
2542                         ast_cdr_start(chan->cdr);
2543                         ast_cdr_end(chan->cdr);
2544                         /* If the cause wasn't handled properly */
2545                         if (ast_cdr_disposition(chan->cdr,chan->hangupcause))
2546                                 ast_cdr_failed(chan->cdr);
2547                 } else 
2548                         ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2549                 ast_hangup(chan);
2550                 chan = NULL;
2551         }
2552         return chan;
2553 }
2554
2555 struct ast_channel *ast_request_and_dial(const char *type, int format, void *data, int timeout, int *outstate, const char *cidnum, const char *cidname)
2556 {
2557         return __ast_request_and_dial(type, format, data, timeout, outstate, cidnum, cidname, NULL);
2558 }
2559
2560 struct ast_channel *ast_request(const char *type, int format, void *data, int *cause)
2561 {
2562         struct chanlist *chan;
2563         struct ast_channel *c;
2564         int capabilities;
2565         int fmt;
2566         int res;
2567         int foo;
2568
2569         if (!cause)
2570                 cause = &foo;
2571         *cause = AST_CAUSE_NOTDEFINED;
2572
2573         if (AST_LIST_LOCK(&channels)) {
2574                 ast_log(LOG_WARNING, "Unable to lock channel list\n");
2575                 return NULL;
2576         }
2577
2578         AST_LIST_TRAVERSE(&backends, chan, list) {
2579                 if (strcasecmp(type, chan->tech->type))
2580                         continue;
2581
2582                 capabilities = chan->tech->capabilities;
2583                 fmt = format;
2584                 res = ast_translator_best_choice(&fmt, &capabilities);
2585                 if (res < 0) {
2586                         ast_log(LOG_WARNING, "No translator path exists for channel type %s (native %d) to %d\n", type, chan->tech->capabilities, format);
2587                         AST_LIST_UNLOCK(&channels);
2588                         return NULL;
2589                 }
2590                 AST_LIST_UNLOCK(&channels);
2591                 if (!chan->tech->requester)
2592                         return NULL;
2593                 
2594                 if (!(c = chan->tech->requester(type, capabilities, data, cause)))
2595                         return NULL;
2596
2597                 if (c->_state == AST_STATE_DOWN) {
2598                         manager_event(EVENT_FLAG_CALL, "Newchannel",
2599                                       "Channel: %s\r\n"
2600                                       "State: %s\r\n"
2601                                       "CallerID: %s\r\n"
2602                                       "CallerIDName: %s\r\n"
2603                                       "Uniqueid: %s\r\n",
2604                                       c->name, ast_state2str(c->_state),
2605                                       c->cid.cid_num ? c->cid.cid_num : "<unknown>",
2606                                       c->cid.cid_name ? c->cid.cid_name : "<unknown>",
2607                                       c->uniqueid);
2608                 }
2609                 return c;
2610         }
2611
2612         ast_log(LOG_WARNING, "No channel type registered for '%s'\n", type);
2613         *cause = AST_CAUSE_NOSUCHDRIVER;
2614         AST_LIST_UNLOCK(&channels);
2615
2616         return NULL;
2617 }
2618
2619 int ast_call(struct ast_channel *chan, char *addr, int timeout) 
2620 {
2621         /* Place an outgoing call, but don't wait any longer than timeout ms before returning. 
2622            If the remote end does not answer within the timeout, then do NOT hang up, but 
2623            return anyway.  */
2624         int res = -1;
2625         /* Stop if we're a zombie or need a soft hangup */
2626         ast_mutex_lock(&chan->lock);
2627         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) 
2628                 if (chan->tech->call)
2629                         res = chan->tech->call(chan, addr, timeout);
2630         ast_mutex_unlock(&chan->lock);
2631         return res;
2632 }
2633
2634 /*! 
2635   \brief Transfer a call to dest, if the channel supports transfer
2636
2637   Called by: 
2638     \arg app_transfer
2639     \arg the manager interface
2640 */
2641 int ast_transfer(struct ast_channel *chan, char *dest) 
2642 {
2643         int res = -1;
2644
2645         /* Stop if we're a zombie or need a soft hangup */
2646         ast_mutex_lock(&chan->lock);
2647         if (!ast_test_flag(chan, AST_FLAG_ZOMBIE) && !ast_check_hangup(chan)) {
2648                 if (chan->tech->transfer) {
2649                         res = chan->tech->transfer(chan, dest);
2650                         if (!res)
2651                                 res = 1;
2652                 } else
2653                         res = 0;
2654         }
2655         ast_mutex_unlock(&chan->lock);
2656         return res;
2657 }
2658
2659 int ast_readstring(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders)
2660 {
2661         int pos=0;
2662         int to = ftimeout;
2663         int d;
2664
2665         /* XXX Merge with full version? XXX */
2666         /* Stop if we're a zombie or need a soft hangup */
2667         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2668                 return -1;
2669         if (!len)
2670                 return -1;
2671         do {
2672                 if (c->stream) {
2673                         d = ast_waitstream(c, AST_DIGIT_ANY);
2674                         ast_stopstream(c);
2675                         usleep(1000);
2676                         if (!d)
2677                                 d = ast_waitfordigit(c, to);
2678                 } else {
2679                         d = ast_waitfordigit(c, to);
2680                 }
2681                 if (d < 0)
2682                         return -1;
2683                 if (d == 0) {
2684                         s[pos]='\0';
2685                         return 1;
2686                 }
2687                 if (!strchr(enders, d))
2688                         s[pos++] = d;
2689                 if (strchr(enders, d) || (pos >= len)) {
2690                         s[pos]='\0';
2691                         return 0;
2692                 }
2693                 to = timeout;
2694         } while(1);
2695         /* Never reached */
2696         return 0;
2697 }
2698
2699 int ast_readstring_full(struct ast_channel *c, char *s, int len, int timeout, int ftimeout, char *enders, int audiofd, int ctrlfd)
2700 {
2701         int pos=0;
2702         int to = ftimeout;
2703         int d;
2704
2705         /* Stop if we're a zombie or need a soft hangup */
2706         if (ast_test_flag(c, AST_FLAG_ZOMBIE) || ast_check_hangup(c)) 
2707                 return -1;
2708         if (!len)
2709                 return -1;
2710         do {
2711                 if (c->stream) {
2712                         d = ast_waitstream_full(c, AST_DIGIT_ANY, audiofd, ctrlfd);
2713                         ast_stopstream(c);
2714                         usleep(1000);
2715                         if (!d)
2716                                 d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2717                 } else {
2718                         d = ast_waitfordigit_full(c, to, audiofd, ctrlfd);
2719                 }
2720                 if (d < 0)
2721                         return -1;
2722                 if (d == 0) {
2723                         s[pos]='\0';
2724                         return 1;
2725                 }
2726                 if (d == 1) {
2727                         s[pos]='\0';
2728                         return 2;
2729                 }
2730                 if (!strchr(enders, d))
2731                         s[pos++] = d;
2732                 if (strchr(enders, d) || (pos >= len)) {
2733                         s[pos]='\0';
2734                         return 0;
2735                 }
2736                 to = timeout;
2737         } while(1);
2738         /* Never reached */
2739         return 0;
2740 }
2741
2742 int ast_channel_supports_html(struct ast_channel *chan)
2743 {
2744         if (chan->tech->send_html)
2745                 return 1;
2746         return 0;
2747 }
2748
2749 int ast_channel_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
2750 {
2751         if (chan->tech->send_html)
2752                 return chan->tech->send_html(chan, subclass, data, datalen);
2753         return -1;
2754 }
2755
2756 int ast_channel_sendurl(struct ast_channel *chan, const char *url)
2757 {
2758         if (chan->tech->send_html)
2759                 return chan->tech->send_html(chan, AST_HTML_URL, url, strlen(url) + 1);
2760         return -1;
2761 }
2762
2763 int ast_channel_make_compatible(struct ast_channel *chan, struct ast_channel *peer)
2764 {
2765         int src;
2766         int dst;
2767
2768         /* Set up translation from the chan to the peer */
2769         src = chan->nativeformats;
2770         dst = peer->nativeformats;
2771         if (ast_translator_best_choice(&dst, &src) < 0) {
2772                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", chan->name, src, peer->name, dst);
2773                 return -1;
2774         }
2775
2776         /* if the best path is not 'pass through', then
2777            transcoding is needed; if desired, force transcode path
2778            to use SLINEAR between channels */
2779         if ((src != dst) && ast_opt_transcode_via_slin)
2780                 dst = AST_FORMAT_SLINEAR;
2781         if (ast_set_read_format(chan, dst) < 0) {
2782                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", chan->name, dst);
2783                 return -1;
2784         }
2785         if (ast_set_write_format(peer, dst) < 0) {
2786                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", peer->name, dst);
2787                 return -1;
2788         }
2789
2790         /* Set up translation from the peer to the chan */
2791         src = peer->nativeformats;
2792         dst = chan->nativeformats;
2793         if (ast_translator_best_choice(&dst, &src) < 0) {
2794                 ast_log(LOG_WARNING, "No path to translate from %s(%d) to %s(%d)\n", peer->name, src, chan->name, dst);
2795                 return -1;
2796         }
2797         /* if the best path is not 'pass through', then
2798            transcoding is needed; if desired, force transcode path
2799            to use SLINEAR between channels */
2800         if ((src != dst) && ast_opt_transcode_via_slin)
2801                 dst = AST_FORMAT_SLINEAR;
2802         if (ast_set_read_format(peer, dst) < 0) {
2803                 ast_log(LOG_WARNING, "Unable to set read format on channel %s to %d\n", peer->name, dst);
2804                 return -1;
2805         }
2806         if (ast_set_write_format(chan, dst) < 0) {
2807                 ast_log(LOG_WARNING, "Unable to set write format on channel %s to %d\n", chan->name, dst);
2808                 return -1;
2809         }
2810         return 0;
2811 }
2812
2813 int ast_channel_masquerade(struct ast_channel *original, struct ast_channel *clone)
2814 {
2815         struct ast_frame null = { AST_FRAME_NULL, };
2816         int res = -1;
2817
2818         if (original == clone) {
2819                 ast_log(LOG_WARNING, "Can't masquerade channel '%s' into itself!\n", original->name);
2820                 return -1;
2821         }
2822         ast_mutex_lock(&original->lock);
2823         while(ast_mutex_trylock(&clone->lock)) {
2824                 ast_mutex_unlock(&original->lock);
2825                 usleep(1);
2826                 ast_mutex_lock(&original->lock);
2827         }
2828         ast_log(LOG_DEBUG, "Planning to masquerade channel %s into the structure of %s\n",
2829                 clone->name, original->name);
2830         if (original->masq) {
2831                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2832                         original->masq->name, original->name);
2833         } else if (clone->masqr) {
2834                 ast_log(LOG_WARNING, "%s is already going to masquerade as %s\n", 
2835                         clone->name, clone->masqr->name);
2836         } else {
2837                 original->masq = clone;
2838                 clone->masqr = original;
2839                 ast_queue_frame(original, &null);
2840                 ast_queue_frame(clone, &null);
2841                 ast_log(LOG_DEBUG, "Done planning to masquerade channel %s into the structure of %s\n", clone->name, original->name);
2842                 res = 0;
2843         }
2844         ast_mutex_unlock(&clone->lock);
2845         ast_mutex_unlock(&original->lock);
2846         return res;
2847 }
2848
2849 void ast_change_name(struct ast_channel *chan, char *newname)
2850 {
2851         char tmp[256];
2852         ast_copy_string(tmp, chan->name, sizeof(tmp));
2853         ast_copy_string(chan->name, newname, sizeof(chan->name));
2854         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", tmp, chan->name, chan->uniqueid);
2855 }
2856
2857 void ast_channel_inherit_variables(const struct ast_channel *parent, struct ast_channel *child)
2858 {
2859         struct ast_var_t *current, *newvar;
2860         const char *varname;
2861
2862         AST_LIST_TRAVERSE(&parent->varshead, current, entries) {
2863                 int vartype = 0;
2864
2865                 varname = ast_var_full_name(current);
2866                 if (!varname)
2867                         continue;
2868
2869                 if (varname[0] == '_') {
2870                         vartype = 1;
2871                         if (varname[1] == '_')
2872                                 vartype = 2;
2873                 }
2874
2875                 switch (vartype) {
2876                 case 1:
2877                         newvar = ast_var_assign(&varname[1], ast_var_value(current));
2878                         if (newvar) {
2879                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2880                                 if (option_debug)
2881                                         ast_log(LOG_DEBUG, "Copying soft-transferable variable %s.\n", ast_var_name(newvar));
2882                         }
2883                         break;
2884                 case 2:
2885                         newvar = ast_var_assign(ast_var_full_name(current), ast_var_value(current));
2886                         if (newvar) {
2887                                 AST_LIST_INSERT_TAIL(&child->varshead, newvar, entries);
2888                                 if (option_debug)
2889                                         ast_log(LOG_DEBUG, "Copying hard-transferable variable %s.\n", ast_var_name(newvar));
2890                         }
2891                         break;
2892                 default:
2893                         if (option_debug)
2894                                 ast_log(LOG_DEBUG, "Not copying variable %s.\n", ast_var_name(current));
2895                         break;
2896                 }
2897         }
2898 }
2899
2900 /*!
2901   \brief Clone channel variables from 'clone' channel into 'original' channel
2902    
2903   All variables except those related to app_groupcount are cloned.
2904   Variables are actually _removed_ from 'clone' channel, presumably
2905   because it will subsequently be destroyed.
2906   
2907   \note Assumes locks will be in place on both channels when called.
2908 */
2909 static void clone_variables(struct ast_channel *original, struct ast_channel *clone)
2910 {
2911         struct ast_var_t *varptr;
2912
2913         /* we need to remove all app_groupcount related variables from the original
2914            channel before merging in the clone's variables; any groups assigned to the
2915            original channel should be released, only those assigned to the clone
2916            should remain
2917         */
2918
2919         AST_LIST_TRAVERSE_SAFE_BEGIN(&original->varshead, varptr, entries) {
2920                 if (!strncmp(ast_var_name(varptr), GROUP_CATEGORY_PREFIX, strlen(GROUP_CATEGORY_PREFIX))) {
2921                         AST_LIST_REMOVE(&original->varshead, varptr, entries);
2922                         ast_var_delete(varptr);
2923                 }
2924         }
2925         AST_LIST_TRAVERSE_SAFE_END;
2926
2927         /* Append variables from clone channel into original channel */
2928         /* XXX Is this always correct?  We have to in order to keep MACROS working XXX */
2929         if (AST_LIST_FIRST(&clone->varshead))
2930                 AST_LIST_INSERT_TAIL(&original->varshead, AST_LIST_FIRST(&clone->varshead), entries);
2931 }
2932
2933 /*!
2934   \brief Masquerade a channel
2935
2936   \note Assumes channel will be locked when called 
2937 */
2938 int ast_do_masquerade(struct ast_channel *original)
2939 {
2940         int x,i;
2941         int res=0;
2942         int origstate;
2943         struct ast_frame *cur, *prev;
2944         const struct ast_channel_tech *t;
2945         void *t_pvt;
2946         struct ast_callerid tmpcid;
2947         struct ast_channel *clone = original->masq;
2948         int rformat = original->readformat;
2949         int wformat = original->writeformat;
2950         char newn[100];
2951         char orig[100];
2952         char masqn[100];
2953         char zombn[100];
2954
2955         if (option_debug > 3)
2956                 ast_log(LOG_DEBUG, "Actually Masquerading %s(%d) into the structure of %s(%d)\n",
2957                         clone->name, clone->_state, original->name, original->_state);
2958
2959         /* XXX This is a seriously wacked out operation.  We're essentially putting the guts of
2960            the clone channel into the original channel.  Start by killing off the original
2961            channel's backend.   I'm not sure we're going to keep this function, because 
2962            while the features are nice, the cost is very high in terms of pure nastiness. XXX */
2963
2964         /* We need the clone's lock, too */
2965         ast_mutex_lock(&clone->lock);
2966
2967         ast_log(LOG_DEBUG, "Got clone lock for masquerade on '%s' at %p\n", clone->name, &clone->lock);
2968
2969         /* Having remembered the original read/write formats, we turn off any translation on either
2970            one */
2971         free_translation(clone);
2972         free_translation(original);
2973
2974
2975         /* Unlink the masquerade */
2976         original->masq = NULL;
2977         clone->masqr = NULL;
2978         
2979         /* Save the original name */
2980         ast_copy_string(orig, original->name, sizeof(orig));
2981         /* Save the new name */
2982         ast_copy_string(newn, clone->name, sizeof(newn));
2983         /* Create the masq name */
2984         snprintf(masqn, sizeof(masqn), "%s<MASQ>", newn);
2985                 
2986         /* Copy the name from the clone channel */
2987         ast_copy_string(original->name, newn, sizeof(original->name));
2988
2989         /* Mangle the name of the clone channel */
2990         ast_copy_string(clone->name, masqn, sizeof(clone->name));
2991         
2992         /* Notify any managers of the change, first the masq then the other */
2993         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", newn, masqn, clone->uniqueid);
2994         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", orig, newn, original->uniqueid);
2995
2996         /* Swap the technologies */     
2997         t = original->tech;
2998         original->tech = clone->tech;
2999         clone->tech = t;
3000
3001         t_pvt = original->tech_pvt;
3002         original->tech_pvt = clone->tech_pvt;
3003         clone->tech_pvt = t_pvt;
3004
3005         /* Swap the readq's */
3006         cur = original->readq;
3007         original->readq = clone->readq;
3008         clone->readq = cur;
3009
3010         /* Swap the alertpipes */
3011         for (i = 0; i < 2; i++) {
3012                 x = original->alertpipe[i];
3013                 original->alertpipe[i] = clone->alertpipe[i];
3014                 clone->alertpipe[i] = x;
3015         }
3016
3017         /* Swap the raw formats */
3018         x = original->rawreadformat;
3019         original->rawreadformat = clone->rawreadformat;
3020         clone->rawreadformat = x;
3021         x = original->rawwriteformat;
3022         original->rawwriteformat = clone->rawwriteformat;
3023         clone->rawwriteformat = x;
3024
3025         /* Save any pending frames on both sides.  Start by counting
3026          * how many we're going to need... */
3027         prev = NULL;
3028         x = 0;
3029         for (cur = clone->readq; cur; cur = cur->next) {
3030                 x++;
3031                 prev = cur;
3032         }
3033         /* If we had any, prepend them to the ones already in the queue, and 
3034          * load up the alertpipe */
3035         if (prev) {
3036                 prev->next = original->readq;
3037                 original->readq = clone->readq;
3038                 clone->readq = NULL;
3039                 if (original->alertpipe[1] > -1) {
3040                         for (i = 0; i < x; i++)
3041                                 write(original->alertpipe[1], &x, sizeof(x));
3042                 }
3043         }
3044         clone->_softhangup = AST_SOFTHANGUP_DEV;
3045
3046
3047         /* And of course, so does our current state.  Note we need not
3048            call ast_setstate since the event manager doesn't really consider
3049            these separate.  We do this early so that the clone has the proper
3050            state of the original channel. */
3051         origstate = original->_state;
3052         original->_state = clone->_state;
3053         clone->_state = origstate;
3054
3055         if (clone->tech->fixup){
3056                 res = clone->tech->fixup(original, clone);
3057                 if (res) 
3058                         ast_log(LOG_WARNING, "Fixup failed on channel %s, strange things may happen.\n", clone->name);
3059         }
3060
3061         /* Start by disconnecting the original's physical side */
3062         if (clone->tech->hangup)
3063                 res = clone->tech->hangup(clone);
3064         if (res) {
3065                 ast_log(LOG_WARNING, "Hangup failed!  Strange things may happen!\n");
3066                 ast_mutex_unlock(&clone->lock);
3067                 return -1;
3068         }
3069         
3070         snprintf(zombn, sizeof(zombn), "%s<ZOMBIE>", orig);
3071         /* Mangle the name of the clone channel */
3072         ast_copy_string(clone->name, zombn, sizeof(clone->name));
3073         manager_event(EVENT_FLAG_CALL, "Rename", "Oldname: %s\r\nNewname: %s\r\nUniqueid: %s\r\n", masqn, zombn, clone->uniqueid);
3074
3075         /* Update the type. */
3076         original->type = clone->type;
3077         t_pvt = original->monitor;
3078         original->monitor = clone->monitor;
3079         clone->monitor = t_pvt;
3080         
3081         /* Keep the same language.  */
3082         ast_copy_string(original->language, clone->language, sizeof(original->language));
3083         /* Copy the FD's */
3084         for (x = 0; x < AST_MAX_FDS; x++) {
3085                 original->fds[x] = clone->fds[x];
3086         }
3087         clone_variables(original, clone);
3088         AST_LIST_HEAD_INIT_NOLOCK(&clone->varshead);
3089         /* Presense of ADSI capable CPE follows clone */
3090         original->adsicpe = clone->adsicpe;
3091         /* Bridge remains the same */
3092         /* CDR fields remain the same */
3093         /* XXX What about blocking, softhangup, blocker, and lock and blockproc? XXX */
3094         /* Application and data remain the same */
3095         /* Clone exception  becomes real one, as with fdno */
3096         ast_copy_flags(original, clone, AST_FLAG_EXCEPTION);
3097         original->fdno = clone->fdno;
3098         /* Schedule context remains the same */
3099         /* Stream stuff stays the same */
3100         /* Keep the original state.  The fixup code will need to work with it most likely */
3101
3102         /* Just swap the whole structures, nevermind the allocations, they'll work themselves
3103            out. */
3104         tmpcid = original->cid;
3105         original->cid = clone->cid;
3106         clone->cid = tmpcid;
3107         
3108         /* Restore original timing file descriptor */
3109         original->fds[AST_MAX_FDS - 2] = original->timingfd;
3110         
3111         /* Our native formats are different now */
3112         original->nativeformats = clone->nativeformats;
3113         
3114         /* Context, extension, priority, app data, jump table,  remain the same */
3115         /* pvt switches.  pbx stays the same, as does next */
3116         
3117         /* Set the write format */
3118         ast_set_write_format(original, wformat);
3119
3120         /* Set the read format */
3121         ast_set_read_format(original, rformat);
3122
3123         /* Copy the music class */
3124         ast_copy_string(original->musicclass, clone->musicclass, sizeof(original->musicclass));
3125
3126         ast_log(LOG_DEBUG, "Putting channel %s in %d/%d formats\n", original->name, wformat, rformat);
3127
3128         /* Okay.  Last thing is to let the channel driver know about all this mess, so he
3129            can fix up everything as best as possible */
3130         if (original->tech->fixup) {
3131                 res = original->tech->fixup(clone, original);
3132                 if (res) {
3133                         ast_log(LOG_WARNING, "Channel for type '%s' could not fixup channel %s\n",
3134                                 original->type, original->name);
3135                         ast_mutex_unlock(&clone->lock);
3136                         return -1;
3137                 }
3138         } else
3139                 ast_log(LOG_WARNING, "Channel type '%s' does not have a fixup routine (for %s)!  Bad things may happen.\n",
3140                         original->type, original->name);
3141         
3142         /* Now, at this point, the "clone" channel is totally F'd up.  We mark it as
3143            a zombie so nothing tries to touch it.  If it's already been marked as a
3144            zombie, then free it now (since it already is considered invalid). */
3145         if (ast_test_flag(clone, AST_FLAG_ZOMBIE)) {
3146                 ast_log(LOG_DEBUG, "Destroying channel clone '%s'\n", clone->name);
3147                 ast_mutex_unlock(&clone->lock);
3148                 manager_event(EVENT_FLAG_CALL, "Hangup", 
3149                         "Channel: %s\r\n"
3150                         "Uniqueid: %s\r\n"
3151                         "Cause: %d\r\n"
3152                         "Cause-txt: %s\r\n",
3153                         clone->name, 
3154                         clone->uniqueid, 
3155                         clone->hangupcause,
3156                         ast_cause2str(clone->hangupcause)
3157                         );
3158                 ast_channel_free(clone);
3159         } else {
3160                 struct ast_frame null_frame = { AST_FRAME_NULL, };
3161                 ast_log(LOG_DEBUG, "Released clone lock on '%s'\n", clone->name);
3162                 ast_set_flag(clone, AST_FLAG_ZOMBIE);
3163                 ast_queue_frame(clone, &null_frame);
3164                 ast_mutex_unlock(&clone->lock);
3165         }
3166         
3167         /* Signal any blocker */
3168         if (ast_test_flag(original, AST_FLAG_BLOCKING))
3169                 pthread_kill(original->blocker, SIGURG);
3170         ast_log(LOG_DEBUG, "Done Masquerading %s (%d)\n", original->name, original->_state);
3171         return 0;
3172 }
3173
3174 void ast_set_callerid(struct ast_channel *chan, const char *callerid, const char *calleridname, const char *ani)
3175 {
3176         if (callerid) {
3177                 if (chan->cid.cid_num)
3178                         free(chan->cid.cid_num);
3179                 if (ast_strlen_zero(callerid))
3180                         chan->cid.cid_num = NULL;
3181                 else
3182                         chan->cid.cid_num = strdup(callerid);
3183         }
3184         if (calleridname) {
3185                 if (chan->cid.cid_name)
3186                         free(chan->cid.cid_name);
3187                 if (ast_strlen_zero(calleridname))
3188                         chan->cid.cid_name = NULL;
3189                 else
3190                         chan->cid.cid_name = strdup(calleridname);
3191         }
3192         if (ani) {
3193                 if (chan->cid.cid_ani)
3194                         free(chan->cid.cid_ani);
3195                 if (ast_strlen_zero(ani))
3196                         chan->cid.cid_ani = NULL;
3197                 else
3198                         chan->cid.cid_ani = strdup(ani);
3199         }
3200         if (chan->cdr)
3201                 ast_cdr_setcid(chan->cdr, chan);
3202         manager_event(EVENT_FLAG_CALL, "Newcallerid", 
3203                                 "Channel: %s\r\n"
3204                                 "CallerID: %s\r\n"
3205                                 "CallerIDName: %s\r\n"
3206                                 "Uniqueid: %s\r\n"
3207                                 "CID-CallingPres: %d (%s)\r\n",
3208                                 chan->name, chan->cid.cid_num ? 
3209                                 chan->cid.cid_num : "<Unknown>",
3210                                 chan->cid.cid_name ? 
3211                                 chan->cid.cid_name : "<Unknown>",
3212                                 chan->uniqueid,
3213                                 chan->cid.cid_pres,
3214                                 ast_describe_caller_presentation(chan->cid.cid_pres)
3215                                 );
3216 }
3217
3218 int ast_setstate(struct ast_channel *chan, int state)
3219 {
3220         int oldstate = chan->_state;
3221
3222         if (oldstate == state)
3223                 return 0;
3224
3225         chan->_state = state;
3226         ast_device_state_changed_literal(chan->name);
3227         manager_event(EVENT_FLAG_CALL,
3228                       (oldstate == AST_STATE_DOWN) ? "Newchannel" : "Newstate",
3229                       "Channel: %s\r\n"
3230                       "State: %s\r\n"
3231                       "CallerID: %s\r\n"
3232                       "CallerIDName: %s\r\n"
3233                       "Uniqueid: %s\r\n",
3234                       chan->name, ast_state2str(chan->_state), 
3235                       chan->cid.cid_num ? chan->cid.cid_num : "<unknown>", 
3236                       chan->cid.cid_name ? chan->cid.cid_name : "<unknown>", 
3237                       chan->uniqueid);
3238
3239         return 0;
3240 }
3241
3242 /*! \brief Find bridged channel */
3243 struct ast_channel *ast_bridged_channel(struct ast_channel *chan)
3244 {
3245         struct ast_channel *bridged;
3246         bridged = chan->_bridge;
3247         if (bridged && bridged->tech->bridged_channel) 
3248                 bridged = bridged->tech->bridged_channel(chan, bridged);
3249         return bridged;
3250 }
3251
3252 static void bridge_playfile(struct ast_channel *chan, struct ast_channel *peer, const char *sound, int remain) 
3253 {
3254         int min = 0, sec = 0, check;
3255
3256         check = ast_autoservice_start(peer);
3257         if (check) 
3258                 return;
3259
3260         if (remain > 0) {
3261                 if (remain / 60 > 1) {
3262                         min = remain / 60;
3263                         sec = remain % 60;
3264                 } else {
3265                         sec = remain;
3266                 }
3267         }
3268         
3269         if (!strcmp(sound,"timeleft")) {        /* Queue support */
3270                 ast_streamfile(chan, "vm-youhave", chan->language);
3271                 ast_waitstream(chan, "");
3272                 if (min) {
3273                         ast_say_number(chan, min, AST_DIGIT_ANY, chan->language, (char *) NULL);
3274                         ast_streamfile(chan, "queue-minutes", chan->language);
3275                         ast_waitstream(chan, "");
3276                 }
3277                 if (sec) {
3278                         ast_say_number(chan, sec, AST_DIGIT_ANY, chan->language, (char *) NULL);
3279                         ast_streamfile(chan, "queue-seconds", chan->language);
3280                         ast_waitstream(chan, "");
3281                 }
3282         } else {
3283                 ast_streamfile(chan, sound, chan->language);
3284                 ast_waitstream(chan, "");
3285         }
3286
3287         check = ast_autoservice_stop(peer);
3288 }
3289
3290 static enum ast_bridge_result ast_generic_bridge(struct ast_channel *c0, struct ast_channel *c1,
3291                                                  struct ast_bridge_config *config, struct ast_frame **fo,
3292                                                  struct ast_channel **rc, struct timeval bridge_end)
3293 {
3294         /* Copy voice back and forth between the two channels. */
3295         struct ast_channel *cs[3];
3296         struct ast_frame *f;
3297         struct ast_channel *who = NULL;
3298         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3299         int o0nativeformats;
3300         int o1nativeformats;
3301         int watch_c0_dtmf;
3302         int watch_c1_dtmf;
3303         void *pvt0, *pvt1;
3304         int to;
3305         
3306         cs[0] = c0;
3307         cs[1] = c1;
3308         pvt0 = c0->tech_pvt;
3309         pvt1 = c1->tech_pvt;
3310         o0nativeformats = c0->nativeformats;
3311         o1nativeformats = c1->nativeformats;
3312         watch_c0_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_0;
3313         watch_c1_dtmf = config->flags & AST_BRIDGE_DTMF_CHANNEL_1;
3314
3315         for (;;) {
3316                 if ((c0->tech_pvt != pvt0) || (c1->tech_pvt != pvt1) ||
3317                     (o0nativeformats != c0->nativeformats) ||
3318                     (o1nativeformats != c1->nativeformats)) {
3319                         /* Check for Masquerade, codec changes, etc */
3320                         res = AST_BRIDGE_RETRY;
3321                         break;
3322                 }
3323                 if (bridge_end.tv_sec) {
3324                         to = ast_tvdiff_ms(bridge_end, ast_tvnow());
3325                         if (to <= 0) {
3326                                 res = AST_BRIDGE_RETRY;
3327                                 break;
3328                         }
3329                 } else
3330                         to = -1;
3331                 who = ast_waitfor_n(cs, 2, &to);
3332                 if (!who) {
3333                         ast_log(LOG_DEBUG, "Nobody there, continuing...\n"); 
3334                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3335                                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3336                                         c0->_softhangup = 0;
3337                                 if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3338                                         c1->_softhangup = 0;
3339                                 c0->_bridge = c1;
3340                                 c1->_bridge = c0;
3341                         }
3342                         continue;
3343                 }
3344                 f = ast_read(who);
3345                 if (!f) {
3346                         *fo = NULL;
3347                         *rc = who;
3348                         res = AST_BRIDGE_COMPLETE;
3349                         ast_log(LOG_DEBUG, "Didn't get a frame from channel: %s\n",who->name);
3350                         break;
3351                 }
3352
3353                 if ((f->frametype == AST_FRAME_CONTROL) && !(config->flags & AST_BRIDGE_IGNORE_SIGS)) {
3354                         if ((f->subclass == AST_CONTROL_HOLD) || (f->subclass == AST_CONTROL_UNHOLD) ||
3355                             (f->subclass == AST_CONTROL_VIDUPDATE)) {
3356                                 ast_indicate(who == c0 ? c1 : c0, f->subclass);
3357                         } else {
3358                                 *fo = f;
3359                                 *rc = who;
3360                                 res =  AST_BRIDGE_COMPLETE;
3361                                 ast_log(LOG_DEBUG, "Got a FRAME_CONTROL (%d) frame on channel %s\n", f->subclass, who->name);
3362                                 break;
3363                         }
3364                 }
3365                 if ((f->frametype == AST_FRAME_VOICE) ||
3366                     (f->frametype == AST_FRAME_DTMF) ||
3367                     (f->frametype == AST_FRAME_VIDEO) || 
3368                     (f->frametype == AST_FRAME_IMAGE) ||
3369                     (f->frametype == AST_FRAME_HTML) ||
3370 #if defined(T38_SUPPORT)
3371                     (f->frametype == AST_FRAME_MODEM) ||
3372 #endif
3373                     (f->frametype == AST_FRAME_TEXT)) {
3374                         if (f->frametype == AST_FRAME_DTMF) {
3375                                 if (((who == c0) && watch_c0_dtmf) ||
3376                                     ((who == c1) && watch_c1_dtmf)) {
3377                                         *rc = who;
3378                                         *fo = f;
3379                                         res = AST_BRIDGE_COMPLETE;
3380                                         ast_log(LOG_DEBUG, "Got DTMF on channel (%s)\n", who->name);
3381                                         break;
3382                                 } else {
3383                                         goto tackygoto;
3384                                 }
3385                         } else {
3386 #if 0
3387                                 ast_log(LOG_DEBUG, "Read from %s\n", who->name);
3388                                 if (who == last) 
3389                                         ast_log(LOG_DEBUG, "Servicing channel %s twice in a row?\n", last->name);
3390                                 last = who;
3391 #endif
3392 tackygoto:
3393                                 ast_write((who == c0) ? c1 : c0, f);
3394                         }
3395                 }
3396                 ast_frfree(f);
3397
3398                 /* Swap who gets priority */
3399                 cs[2] = cs[0];
3400                 cs[0] = cs[1];
3401                 cs[1] = cs[2];
3402         }
3403         return res;
3404 }
3405
3406 /*! \brief Bridge two channels together */
3407 enum ast_bridge_result ast_channel_bridge(struct ast_channel *c0, struct ast_channel *c1,
3408                                           struct ast_bridge_config *config, struct ast_frame **fo, struct ast_channel **rc) 
3409 {
3410         struct ast_channel *who = NULL;
3411         enum ast_bridge_result res = AST_BRIDGE_COMPLETE;
3412         int nativefailed=0;
3413         int firstpass;
3414         int o0nativeformats;
3415         int o1nativeformats;
3416         long time_left_ms=0;
3417         struct timeval nexteventts = { 0, };
3418         char caller_warning = 0;
3419         char callee_warning = 0;
3420         int to;
3421
3422         if (c0->_bridge) {
3423                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3424                         c0->name, c0->_bridge->name);
3425                 return -1;
3426         }
3427         if (c1->_bridge) {
3428                 ast_log(LOG_WARNING, "%s is already in a bridge with %s\n", 
3429                         c1->name, c1->_bridge->name);
3430                 return -1;
3431         }
3432         
3433         /* Stop if we're a zombie or need a soft hangup */
3434         if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3435             ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) 
3436                 return -1;
3437
3438         *fo = NULL;
3439         firstpass = config->firstpass;
3440         config->firstpass = 0;
3441
3442         if (ast_tvzero(config->start_time))
3443                 config->start_time = ast_tvnow();
3444         time_left_ms = config->timelimit;
3445
3446         caller_warning = ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING);
3447         callee_warning = ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING);
3448
3449         if (config->start_sound && firstpass) {
3450                 if (caller_warning)
3451                         bridge_playfile(c0, c1, config->start_sound, time_left_ms / 1000);
3452                 if (callee_warning)
3453                         bridge_playfile(c1, c0, config->start_sound, time_left_ms / 1000);
3454         }
3455
3456         /* Keep track of bridge */
3457         c0->_bridge = c1;
3458         c1->_bridge = c0;
3459         
3460         manager_event(EVENT_FLAG_CALL, "Link", 
3461                       "Channel1: %s\r\n"
3462                       "Channel2: %s\r\n"
3463                       "Uniqueid1: %s\r\n"
3464                       "Uniqueid2: %s\r\n"
3465                       "CallerID1: %s\r\n"
3466                       "CallerID2: %s\r\n",
3467                       c0->name, c1->name, c0->uniqueid, c1->uniqueid, c0->cid.cid_num, c1->cid.cid_num);
3468                                                                         
3469         o0nativeformats = c0->nativeformats;
3470         o1nativeformats = c1->nativeformats;
3471
3472         if (config->timelimit) {
3473                 nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3474                 if (caller_warning || callee_warning)
3475                         nexteventts = ast_tvsub(nexteventts, ast_samp2tv(config->play_warning, 1000));
3476         }
3477
3478         for (/* ever */;;) {
3479                 to = -1;
3480                 if (config->timelimit) {
3481                         struct timeval now;
3482                         now = ast_tvnow();
3483                         to = ast_tvdiff_ms(nexteventts, now);
3484                         if (to < 0)
3485                                 to = 0;
3486                         time_left_ms = config->timelimit - ast_tvdiff_ms(now, config->start_time);
3487                         if (time_left_ms < to)
3488                                 to = time_left_ms;
3489
3490                         if (time_left_ms <= 0) {
3491                                 if (caller_warning && config->end_sound)
3492                                         bridge_playfile(c0, c1, config->end_sound, 0);
3493                                 if (callee_warning && config->end_sound)
3494                                         bridge_playfile(c1, c0, config->end_sound, 0);
3495                                 *fo = NULL;
3496                                 if (who) 
3497                                         *rc = who;
3498                                 res = 0;
3499                                 break;
3500                         }
3501                         
3502                         if (!to) {
3503                                 if (time_left_ms >= 5000) {
3504                                         /* force the time left to round up if appropriate */
3505                                         if (caller_warning && config->warning_sound && config->play_warning)
3506                                                 bridge_playfile(c0, c1, config->warning_sound,
3507                                                                 (time_left_ms + 500) / 1000);
3508                                         if (callee_warning && config->warning_sound && config->play_warning)
3509                                                 bridge_playfile(c1, c0, config->warning_sound,
3510                                                                 (time_left_ms + 500) / 1000);
3511                                 }
3512                                 if (config->warning_freq) {
3513                                         nexteventts = ast_tvadd(nexteventts, ast_samp2tv(config->warning_freq, 1000));
3514                                 } else
3515                                         nexteventts = ast_tvadd(config->start_time, ast_samp2tv(config->timelimit, 1000));
3516                         }
3517                 }
3518
3519                 if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE || c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE) {
3520                         if (c0->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3521                                 c0->_softhangup = 0;
3522                         if (c1->_softhangup == AST_SOFTHANGUP_UNBRIDGE)
3523                                 c1->_softhangup = 0;
3524                         c0->_bridge = c1;
3525                         c1->_bridge = c0;
3526                         ast_log(LOG_DEBUG, "Unbridge signal received. Ending native bridge.\n");
3527                         continue;
3528                 }
3529                 
3530                 /* Stop if we're a zombie or need a soft hangup */
3531                 if (ast_test_flag(c0, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c0) ||
3532                     ast_test_flag(c1, AST_FLAG_ZOMBIE) || ast_check_hangup_locked(c1)) {
3533                         *fo = NULL;
3534                         if (who)
3535                                 *rc = who;
3536                         res = 0;
3537                         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",
3538                                 c0->name, c1->name,
3539                                 ast_test_flag(c0, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3540                                 ast_check_hangup(c0) ? "Yes" : "No",
3541                                 ast_test_flag(c1, AST_FLAG_ZOMBIE) ? "Yes" : "No",
3542                                 ast_check_hangup(c1) ? "Yes" : "No");
3543                         break;
3544                 }
3545
3546                 if (c0->tech->bridge &&
3547                     (config->timelimit == 0) &&
3548                     (c0->tech->bridge == c1->tech->bridge) &&
3549                     !nativefailed && !c0->monitor && !c1->monitor &&
3550                     !c0->spies && !c1->spies) {
3551                         /* Looks like they share a bridge method and nothing else is in the way */
3552                         ast_set_flag(c0, AST_FLAG_NBRIDGE);
3553                         ast_set_flag(c1, AST_FLAG_NBRIDGE);
3554                         if ((res = c0->tech->bridge(c0, c1, config->flags, fo, rc, to)) == AST_BRIDGE_COMPLETE) {
3555                                 manager_event(EVENT_FLAG_CALL, "Unlink", 
3556                                               "Channel1: %s\r\n"
3557                                               "Channel2: %s\r\n"
3558                                               "Uniqueid1: %s\r\n"
3559                                               "Uniqueid2: %s\r\n"
3560                                               "CallerID1: %s\r\n"
3561                                               "CallerID2: %s\r\n",