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