update dependency information to match new names for dependencies
[asterisk/asterisk.git] / channels / chan_zap.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 Zaptel Pseudo TDM interface 
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * Connects to the zaptel telephony library as well as 
26  * libpri. Libpri is optional and needed only if you are
27  * going to use ISDN connections.
28  *
29  * You need to install libraries before you attempt to compile
30  * and install the zaptel channel.
31  *
32  * \par See also
33  * \arg \ref Config_zap
34  *
35  * \ingroup channel_drivers
36  *
37  * \todo Deprecate the "musiconhold" configuration option post 1.4
38  */
39
40 /*** MODULEINFO
41         <depend>zaptel</depend>
42         <depend>tonezone</depend>
43         <use>pri</use>
44  ***/
45
46 #include "asterisk.h"
47
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
49
50 #include <stdio.h>
51 #include <string.h>
52 #ifdef __NetBSD__
53 #include <pthread.h>
54 #include <signal.h>
55 #else
56 #include <sys/signal.h>
57 #endif
58 #include <errno.h>
59 #include <stdlib.h>
60 #if !defined(SOLARIS) && !defined(__FreeBSD__)
61 #include <stdint.h>
62 #endif
63 #include <unistd.h>
64 #include <sys/ioctl.h>
65 #include <math.h>
66 #include <ctype.h>
67 #include <zaptel/zaptel.h>
68 #include <zaptel/tonezone.h>
69
70 #ifdef HAVE_LIBPRI
71 #include <libpri.h>
72 #endif
73
74 #include "asterisk/lock.h"
75 #include "asterisk/channel.h"
76 #include "asterisk/config.h"
77 #include "asterisk/logger.h"
78 #include "asterisk/module.h"
79 #include "asterisk/pbx.h"
80 #include "asterisk/options.h"
81 #include "asterisk/file.h"
82 #include "asterisk/ulaw.h"
83 #include "asterisk/alaw.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/adsi.h"
86 #include "asterisk/cli.h"
87 #include "asterisk/cdr.h"
88 #include "asterisk/features.h"
89 #include "asterisk/musiconhold.h"
90 #include "asterisk/say.h"
91 #include "asterisk/tdd.h"
92 #include "asterisk/app.h"
93 #include "asterisk/dsp.h"
94 #include "asterisk/astdb.h"
95 #include "asterisk/manager.h"
96 #include "asterisk/causes.h"
97 #include "asterisk/term.h"
98 #include "asterisk/utils.h"
99 #include "asterisk/transcap.h"
100 #include "asterisk/stringfields.h"
101 #include "asterisk/abstract_jb.h"
102 #include "asterisk/smdi.h"
103 #include "asterisk/astobj.h"
104 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
105
106 /*! Global jitterbuffer configuration - by default, jb is disabled */
107 static struct ast_jb_conf default_jbconf =
108 {
109         .flags = 0,
110         .max_size = -1,
111         .resync_threshold = -1,
112         .impl = ""
113 };
114 static struct ast_jb_conf global_jbconf;
115
116 #if !defined(ZT_SIG_EM_E1) || (defined(HAVE_LIBPRI) && !defined(ZT_SIG_HARDHDLC))
117 #error "Your zaptel is too old.  Please update"
118 #endif
119
120 #ifndef ZT_TONEDETECT
121 /* Work around older code with no tone detect */
122 #define ZT_EVENT_DTMFDOWN 0
123 #define ZT_EVENT_DTMFUP 0
124 #endif
125
126 /* define this to send PRI user-user information elements */
127 #undef SUPPORT_USERUSER
128
129 /*! 
130  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
131  * the user hangs up to reset the state machine so ring works properly.
132  * This is used to be able to support kewlstart by putting the zhone in
133  * groundstart mode since their forward disconnect supervision is entirely
134  * broken even though their documentation says it isn't and their support
135  * is entirely unwilling to provide any assistance with their channel banks
136  * even though their web site says they support their products for life.
137  */
138 /* #define ZHONE_HACK */
139
140 /*! \note
141  * Define if you want to check the hook state for an FXO (FXS signalled) interface
142  * before dialing on it.  Certain FXO interfaces always think they're out of
143  * service with this method however.
144  */
145 /* #define ZAP_CHECK_HOOKSTATE */
146
147 /*! \brief Typically, how many rings before we should send Caller*ID */
148 #define DEFAULT_CIDRINGS 1
149
150 #define CHANNEL_PSEUDO -12
151
152 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
153
154 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
155 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FGC_CAMA) || ((p)->sig == SIG_FGC_CAMAMF) || ((p)->sig == SIG_FEATB)) 
156
157 static const char tdesc[] = "Zapata Telephony Driver"
158 #ifdef HAVE_LIBPRI
159                " w/PRI"
160 #endif
161 ;
162
163 static const char config[] = "zapata.conf";
164
165 #define SIG_EM          ZT_SIG_EM
166 #define SIG_EMWINK      (0x0100000 | ZT_SIG_EM)
167 #define SIG_FEATD       (0x0200000 | ZT_SIG_EM)
168 #define SIG_FEATDMF     (0x0400000 | ZT_SIG_EM)
169 #define SIG_FEATB       (0x0800000 | ZT_SIG_EM)
170 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
171 #define SIG_FEATDMF_TA  (0x2000000 | ZT_SIG_EM)
172 #define SIG_FGC_CAMA    (0x4000000 | ZT_SIG_EM)
173 #define SIG_FGC_CAMAMF  (0x8000000 | ZT_SIG_EM)
174 #define SIG_FXSLS       ZT_SIG_FXSLS
175 #define SIG_FXSGS       ZT_SIG_FXSGS
176 #define SIG_FXSKS       ZT_SIG_FXSKS
177 #define SIG_FXOLS       ZT_SIG_FXOLS
178 #define SIG_FXOGS       ZT_SIG_FXOGS
179 #define SIG_FXOKS       ZT_SIG_FXOKS
180 #define SIG_PRI         ZT_SIG_CLEAR
181 #define SIG_SF          ZT_SIG_SF
182 #define SIG_SFWINK      (0x0100000 | ZT_SIG_SF)
183 #define SIG_SF_FEATD    (0x0200000 | ZT_SIG_SF)
184 #define SIG_SF_FEATDMF  (0x0400000 | ZT_SIG_SF)
185 #define SIG_SF_FEATB    (0x0800000 | ZT_SIG_SF)
186 #define SIG_EM_E1       ZT_SIG_EM_E1
187 #define SIG_GR303FXOKS  (0x0100000 | ZT_SIG_FXOKS)
188 #define SIG_GR303FXSKS  (0x0100000 | ZT_SIG_FXSKS)
189
190 #define NUM_SPANS               32
191 #define NUM_DCHANS              4       /*!< No more than 4 d-channels */
192 #define MAX_CHANNELS    672             /*!< No more than a DS3 per trunk group */
193
194 #define CHAN_PSEUDO     -2
195
196 #define DCHAN_PROVISIONED (1 << 0)
197 #define DCHAN_NOTINALARM  (1 << 1)
198 #define DCHAN_UP          (1 << 2)
199
200 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
201
202 static char context[AST_MAX_CONTEXT] = "default";
203 static char cid_num[256] = "";
204 static char cid_name[256] = "";
205 static char defaultcic[64] = "";
206 static char defaultozz[64] = "";
207
208 static char language[MAX_LANGUAGE] = "";
209 static char musicclass[MAX_MUSICCLASS] = "";
210 static char progzone[10] = "";
211
212 static int usedistinctiveringdetection = 0;
213 static int distinctiveringaftercid = 0;
214
215 static int transfertobusy = 1;
216
217 static int use_callerid = 1;
218 static int cid_signalling = CID_SIG_BELL;
219 static int cid_start = CID_START_RING;
220 static int zaptrcallerid = 0;
221 static int cur_signalling = -1;
222 static int cur_outsignalling = -1;
223
224 static ast_group_t cur_group = 0;
225 static ast_group_t cur_callergroup = 0;
226 static ast_group_t cur_pickupgroup = 0;
227 static int relaxdtmf = 0;
228
229 static int immediate = 0;
230
231 static int stripmsd = 0;
232
233 static int callwaiting = 0;
234
235 static int callwaitingcallerid = 0;
236
237 static int hidecallerid = 0;
238
239 static int restrictcid = 0;
240
241 static int use_callingpres = 0;
242
243 static int callreturn = 0;
244
245 static int threewaycalling = 0;
246
247 static int transfer = 0;
248
249 static int canpark = 0;
250
251 static int cancallforward = 0;
252
253 static float rxgain = 0.0;
254
255 static float txgain = 0.0;
256
257 static int tonezone = -1;
258
259 static int echocancel;
260
261 static int echotraining;
262
263 static int pulse;
264
265 static int echocanbridged = 0;
266
267 static int busydetect = 0;
268
269 static int busycount = 3;
270 static int busy_tonelength = 0;
271 static int busy_quietlength = 0;
272
273 static int callprogress = 0;
274
275 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
276
277 static char mailbox[AST_MAX_EXTENSION];
278
279 static int amaflags = 0;
280
281 static int adsi = 0;
282 static int use_smdi = 0;
283 static char smdi_port[SMDI_MAX_FILENAME_LEN] = "/dev/ttyS0";
284 static int numbufs = 4;
285
286 static int cur_prewink = -1;
287 static int cur_preflash = -1;
288 static int cur_wink = -1;
289 static int cur_flash = -1;
290 static int cur_start = -1;
291 static int cur_rxwink = -1;
292 static int cur_rxflash = -1;
293 static int cur_debounce = -1;
294 static int cur_priexclusive = 0;
295
296 static int priindication_oob = 0;
297
298 #ifdef HAVE_LIBPRI
299 static int minunused = 2;
300 static int minidle = 0;
301 static char idleext[AST_MAX_EXTENSION];
302 static char idledial[AST_MAX_EXTENSION];
303 static int overlapdial = 0;
304 static int facilityenable = 0;
305 static char internationalprefix[10] = "";
306 static char nationalprefix[10] = "";
307 static char localprefix[20] = "";
308 static char privateprefix[20] = "";
309 static char unknownprefix[20] = "";
310 static long resetinterval = 3600;       /*!< How often (in seconds) to reset unused channels. Default 1 hour. */
311 static struct ast_channel inuse;
312 #ifdef PRI_GETSET_TIMERS
313 static int pritimers[PRI_MAX_TIMERS];
314 #endif
315 static int pridebugfd = -1;
316 static char pridebugfilename[1024] = "";
317 #endif
318
319 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
320 static int firstdigittimeout = 16000;
321
322 /*! \brief How long to wait for following digits (FXO logic) */
323 static int gendigittimeout = 8000;
324
325 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
326 static int matchdigittimeout = 3000;
327
328 static int usecnt = 0;
329 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
330
331 /*! \brief Protect the interface list (of zt_pvt's) */
332 AST_MUTEX_DEFINE_STATIC(iflock);
333
334
335 static int ifcount = 0;
336
337 #ifdef HAVE_LIBPRI
338 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
339 #endif
340
341 /*! \brief Whether we answer on a Polarity Switch event */
342 static int answeronpolarityswitch = 0;
343
344 /*! \brief Whether we hang up on a Polarity Switch event */
345 static int hanguponpolarityswitch = 0;
346
347 /*! \brief How long (ms) to ignore Polarity Switch events after we answer a call */
348 static int polarityonanswerdelay = 600;
349
350 /*! \brief When to send the CallerID signals (rings) */
351 static int sendcalleridafter = DEFAULT_CIDRINGS;
352
353 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
354    when it's doing something critical. */
355 AST_MUTEX_DEFINE_STATIC(monlock);
356
357 /*! \brief This is the thread for the monitor which checks for input on the channels
358    which are not currently in use. */
359 static pthread_t monitor_thread = AST_PTHREADT_NULL;
360
361 static int restart_monitor(void);
362
363 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
364
365 static int zt_sendtext(struct ast_channel *c, const char *text);
366
367 /*! \brief Avoid the silly zt_getevent which ignores a bunch of events */
368 static inline int zt_get_event(int fd)
369 {
370         int j;
371         if (ioctl(fd, ZT_GETEVENT, &j) == -1)
372                 return -1;
373         return j;
374 }
375
376 /*! \brief Avoid the silly zt_waitevent which ignores a bunch of events */
377 static inline int zt_wait_event(int fd)
378 {
379         int i, j = 0;
380         i = ZT_IOMUX_SIGEVENT;
381         if (ioctl(fd, ZT_IOMUX, &i) == -1)
382                 return -1;
383         if (ioctl(fd, ZT_GETEVENT, &j) == -1)
384                 return -1;
385         return j;
386 }
387
388 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
389 #define READ_SIZE 160
390
391 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
392 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
393
394 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /*!< 300 ms */
395 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /*!< 300 ms */
396 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /*!< 500 ms */
397 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /*!< 2000 ms */
398 #define DEFAULT_RINGT                           ( (8000 * 8) / READ_SIZE)
399
400 struct zt_pvt;
401
402 static int ringt_base = DEFAULT_RINGT;
403
404 #ifdef HAVE_LIBPRI
405
406 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
407 #define PRI_CHANNEL(p) ((p) & 0xff)
408 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
409 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
410
411 struct zt_pri {
412         pthread_t master;                                               /*!< Thread of master */
413         ast_mutex_t lock;                                               /*!< Mutex */
414         char idleext[AST_MAX_EXTENSION];                                /*!< Where to idle extra calls */
415         char idlecontext[AST_MAX_CONTEXT];                              /*!< What context to use for idle */
416         char idledial[AST_MAX_EXTENSION];                               /*!< What to dial before dumping */
417         int minunused;                                                  /*!< Min # of channels to keep empty */
418         int minidle;                                                    /*!< Min # of "idling" calls to keep active */
419         int nodetype;                                                   /*!< Node type */
420         int switchtype;                                                 /*!< Type of switch to emulate */
421         int nsf;                                                        /*!< Network-Specific Facilities */
422         int dialplan;                                                   /*!< Dialing plan */
423         int localdialplan;                                              /*!< Local dialing plan */
424         char internationalprefix[10];                                   /*!< country access code ('00' for european dialplans) */
425         char nationalprefix[10];                                        /*!< area access code ('0' for european dialplans) */
426         char localprefix[20];                                           /*!< area access code + area code ('0'+area code for european dialplans) */
427         char privateprefix[20];                                         /*!< for private dialplans */
428         char unknownprefix[20];                                         /*!< for unknown dialplans */
429         int dchannels[NUM_DCHANS];                                      /*!< What channel are the dchannels on */
430         int trunkgroup;                                                 /*!< What our trunkgroup is */
431         int mastertrunkgroup;                                           /*!< What trunk group is our master */
432         int prilogicalspan;                                             /*!< Logical span number within trunk group */
433         int numchans;                                                   /*!< Num of channels we represent */
434         int overlapdial;                                                /*!< In overlap dialing mode */
435         int facilityenable;                                             /*!< Enable facility IEs */
436         struct pri *dchans[NUM_DCHANS];                                 /*!< Actual d-channels */
437         int dchanavail[NUM_DCHANS];                                     /*!< Whether each channel is available */
438         struct pri *pri;                                                /*!< Currently active D-channel */
439         int debug;
440         int fds[NUM_DCHANS];                                            /*!< FD's for d-channels */
441         int offset;
442         int span;
443         int resetting;
444         int resetpos;
445         time_t lastreset;                                               /*!< time when unused channels were last reset */
446         long resetinterval;                                             /*!< Interval (in seconds) for resetting unused channels */
447         struct zt_pvt *pvts[MAX_CHANNELS];                              /*!< Member channel pvt structs */
448         struct zt_pvt *crvs;                                            /*!< Member CRV structs */
449         struct zt_pvt *crvend;                                          /*!< Pointer to end of CRV structs */
450 };
451
452
453 static struct zt_pri pris[NUM_SPANS];
454
455 static int pritype = PRI_CPE;
456
457 #if 0
458 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
459 #else
460 #define DEFAULT_PRI_DEBUG 0
461 #endif
462
463 static inline void pri_rel(struct zt_pri *pri)
464 {
465         ast_mutex_unlock(&pri->lock);
466 }
467
468 static int switchtype = PRI_SWITCH_NI2;
469 static int nsf = PRI_NSF_NONE;
470 static int dialplan = PRI_NATIONAL_ISDN + 1;
471 static int localdialplan = PRI_NATIONAL_ISDN + 1;
472
473 #else
474 /*! Shut up the compiler */
475 struct zt_pri;
476 #endif
477
478 #define SUB_REAL        0                       /*!< Active call */
479 #define SUB_CALLWAIT    1                       /*!< Call-Waiting call on hold */
480 #define SUB_THREEWAY    2                       /*!< Three-way call */
481
482 /* Polarity states */
483 #define POLARITY_IDLE   0
484 #define POLARITY_REV    1
485
486
487 static struct zt_distRings drings;
488
489 struct distRingData {
490         int ring[3];
491 };
492 struct ringContextData {
493         char contextData[AST_MAX_CONTEXT];
494 };
495 struct zt_distRings {
496         struct distRingData ringnum[3];
497         struct ringContextData ringContext[3];
498 };
499
500 static char *subnames[] = {
501         "Real",
502         "Callwait",
503         "Threeway"
504 };
505
506 struct zt_subchannel {
507         int zfd;
508         struct ast_channel *owner;
509         int chan;
510         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
511         struct ast_frame f;             /*!< One frame for each channel.  How did this ever work before? */
512         unsigned int needringing:1;
513         unsigned int needbusy:1;
514         unsigned int needcongestion:1;
515         unsigned int needcallerid:1;
516         unsigned int needanswer:1;
517         unsigned int needflash:1;
518         unsigned int linear:1;
519         unsigned int inthreeway:1;
520         ZT_CONFINFO curconf;
521 };
522
523 #define CONF_USER_REAL          (1 << 0)
524 #define CONF_USER_THIRDCALL     (1 << 1)
525
526 #define MAX_SLAVES      4
527
528 static struct zt_pvt {
529         ast_mutex_t lock;
530         struct ast_channel *owner;                      /*!< Our current active owner (if applicable) */
531                                                         /*!< Up to three channels can be associated with this call */
532                 
533         struct zt_subchannel sub_unused;                /*!< Just a safety precaution */
534         struct zt_subchannel subs[3];                   /*!< Sub-channels */
535         struct zt_confinfo saveconf;                    /*!< Saved conference info */
536
537         struct zt_pvt *slaves[MAX_SLAVES];              /*!< Slave to us (follows our conferencing) */
538         struct zt_pvt *master;                          /*!< Master to us (we follow their conferencing) */
539         int inconference;                               /*!< If our real should be in the conference */
540         
541         int sig;                                        /*!< Signalling style */
542         int radio;                                      /*!< radio type */
543         int outsigmod;                                  /*!< Outbound Signalling style (modifier) */
544         int oprmode;                                    /*!< "Operator Services" mode */
545         struct zt_pvt *oprpeer;                         /*!< "Operator Services" peer tech_pvt ptr */
546         float rxgain;
547         float txgain;
548         int tonezone;                                   /*!< tone zone for this chan, or -1 for default */
549         struct zt_pvt *next;                            /*!< Next channel in list */
550         struct zt_pvt *prev;                            /*!< Prev channel in list */
551
552         /* flags */
553         unsigned int adsi:1;
554         unsigned int answeronpolarityswitch:1;
555         unsigned int busydetect:1;
556         unsigned int callreturn:1;
557         unsigned int callwaiting:1;
558         unsigned int callwaitingcallerid:1;
559         unsigned int cancallforward:1;
560         unsigned int canpark:1;
561         unsigned int confirmanswer:1;                   /*!< Wait for '#' to confirm answer */
562         unsigned int destroy:1;
563         unsigned int didtdd:1;                          /*!< flag to say its done it once */
564         unsigned int dialednone:1;
565         unsigned int dialing:1;
566         unsigned int digital:1;
567         unsigned int dnd:1;
568         unsigned int echobreak:1;
569         unsigned int echocanbridged:1;
570         unsigned int echocanon:1;
571         unsigned int faxhandled:1;                      /*!< Has a fax tone already been handled? */
572         unsigned int firstradio:1;
573         unsigned int hanguponpolarityswitch:1;
574         unsigned int hardwaredtmf:1;
575         unsigned int hidecallerid;
576         unsigned int ignoredtmf:1;
577         unsigned int immediate:1;                       /*!< Answer before getting digits? */
578         unsigned int inalarm:1;
579         unsigned int mate:1;                            /*!< flag to say its in MATE mode */
580         unsigned int outgoing:1;
581         unsigned int overlapdial:1;
582         unsigned int permcallwaiting:1;
583         unsigned int permhidecallerid:1;                /*!< Whether to hide our outgoing caller ID or not */
584         unsigned int priindication_oob:1;
585         unsigned int priexclusive:1;
586         unsigned int pulse:1;
587         unsigned int pulsedial:1;                       /*!< whether a pulse dial phone is detected */
588         unsigned int restrictcid:1;                     /*!< Whether restrict the callerid -> only send ANI */
589         unsigned int threewaycalling:1;
590         unsigned int transfer:1;
591         unsigned int use_callerid:1;                    /*!< Whether or not to use caller id on this channel */
592         unsigned int use_callingpres:1;                 /*!< Whether to use the callingpres the calling switch sends */
593         unsigned int usedistinctiveringdetection:1;
594         unsigned int zaptrcallerid:1;                   /*!< should we use the callerid from incoming call on zap transfer or not */
595         unsigned int transfertobusy:1;                  /*!< allow flash-transfers to busy channels */
596 #if defined(HAVE_LIBPRI)
597         unsigned int alerting:1;
598         unsigned int alreadyhungup:1;
599         unsigned int isidlecall:1;
600         unsigned int proceeding:1;
601         unsigned int progress:1;
602         unsigned int resetting:1;
603         unsigned int setup_ack:1;
604 #endif
605         unsigned int use_smdi:1;                /* Whether to use SMDI on this channel */
606         struct ast_smdi_interface *smdi_iface;  /* The serial port to listen for SMDI data on */
607
608         struct zt_distRings drings;
609
610         char context[AST_MAX_CONTEXT];
611         char defcontext[AST_MAX_CONTEXT];
612         char exten[AST_MAX_EXTENSION];
613         char language[MAX_LANGUAGE];
614         char musicclass[MAX_MUSICCLASS];
615 #ifdef PRI_ANI
616         char cid_ani[AST_MAX_EXTENSION];
617 #endif
618         char cid_num[AST_MAX_EXTENSION];
619         int cid_ton;                                    /*!< Type Of Number (TON) */
620         char cid_name[AST_MAX_EXTENSION];
621         char lastcid_num[AST_MAX_EXTENSION];
622         char lastcid_name[AST_MAX_EXTENSION];
623         char *origcid_num;                              /*!< malloced original callerid */
624         char *origcid_name;                             /*!< malloced original callerid */
625         char callwait_num[AST_MAX_EXTENSION];
626         char callwait_name[AST_MAX_EXTENSION];
627         char rdnis[AST_MAX_EXTENSION];
628         char dnid[AST_MAX_EXTENSION];
629         unsigned int group;
630         int law;
631         int confno;                                     /*!< Our conference */
632         int confusers;                                  /*!< Who is using our conference */
633         int propconfno;                                 /*!< Propagated conference number */
634         ast_group_t callgroup;
635         ast_group_t pickupgroup;
636         int channel;                                    /*!< Channel Number or CRV */
637         int span;                                       /*!< Span number */
638         time_t guardtime;                               /*!< Must wait this much time before using for new call */
639         int cid_signalling;                             /*!< CID signalling type bell202 or v23 */
640         int cid_start;                                  /*!< CID start indicator, polarity or ring */
641         int callingpres;                                /*!< The value of callling presentation that we're going to use when placing a PRI call */
642         int callwaitingrepeat;                          /*!< How many samples to wait before repeating call waiting */
643         int cidcwexpire;                                /*!< When to expire our muting for CID/CW */
644         unsigned char *cidspill;
645         int cidpos;
646         int cidlen;
647         int ringt;
648         int ringt_base;
649         int stripmsd;
650         int callwaitcas;
651         int callwaitrings;
652         int echocancel;
653         int echotraining;
654         char echorest[20];
655         int busycount;
656         int busy_tonelength;
657         int busy_quietlength;
658         int callprogress;
659         struct timeval flashtime;                       /*!< Last flash-hook time */
660         struct ast_dsp *dsp;
661         int cref;                                       /*!< Call reference number */
662         ZT_DIAL_OPERATION dop;
663         int whichwink;                                  /*!< SIG_FEATDMF_TA Which wink are we on? */
664         char finaldial[64];
665         char accountcode[AST_MAX_ACCOUNT_CODE];         /*!< Account code */
666         int amaflags;                                   /*!< AMA Flags */
667         struct tdd_state *tdd;                          /*!< TDD flag */
668         char call_forward[AST_MAX_EXTENSION];
669         char mailbox[AST_MAX_EXTENSION];
670         char dialdest[256];
671         int onhooktime;
672         int msgstate;
673         int distinctivering;                            /*!< Which distinctivering to use */
674         int cidrings;                                   /*!< Which ring to deliver CID on */
675         int dtmfrelax;                                  /*!< whether to run in relaxed DTMF mode */
676         int fake_event;
677         int polarityonanswerdelay;
678         struct timeval polaritydelaytv;
679         int sendcalleridafter;
680 #ifdef HAVE_LIBPRI
681         struct zt_pri *pri;
682         struct zt_pvt *bearer;
683         struct zt_pvt *realcall;
684         q931_call *call;
685         int prioffset;
686         int logicalspan;
687 #endif  
688         int polarity;
689         int dsp_features;
690 } *iflist = NULL, *ifend = NULL;
691
692 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
693 static int zt_digit(struct ast_channel *ast, char digit);
694 static int zt_sendtext(struct ast_channel *c, const char *text);
695 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
696 static int zt_hangup(struct ast_channel *ast);
697 static int zt_answer(struct ast_channel *ast);
698 struct ast_frame *zt_read(struct ast_channel *ast);
699 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
700 struct ast_frame *zt_exception(struct ast_channel *ast);
701 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
702 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
703 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
704 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len); 
705
706 static const struct ast_channel_tech zap_tech = {
707         .type = "Zap",
708         .description = tdesc,
709         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
710         .requester = zt_request,
711         .send_digit = zt_digit,
712         .send_text = zt_sendtext,
713         .call = zt_call,
714         .hangup = zt_hangup,
715         .answer = zt_answer,
716         .read = zt_read,
717         .write = zt_write,
718         .bridge = zt_bridge,
719         .exception = zt_exception,
720         .indicate = zt_indicate,
721         .fixup = zt_fixup,
722         .setoption = zt_setoption,
723         .func_channel_read = zt_func_read,
724 };
725
726 #ifdef HAVE_LIBPRI
727 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
728 #else
729 #define GET_CHANNEL(p) ((p)->channel)
730 #endif
731
732 struct zt_pvt *round_robin[32];
733
734 #ifdef HAVE_LIBPRI
735 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
736 {
737         int res;
738         /* Grab the lock first */
739         do {
740                 res = ast_mutex_trylock(&pri->lock);
741                 if (res) {
742                         ast_mutex_unlock(&pvt->lock);
743                         /* Release the lock and try again */
744                         usleep(1);
745                         ast_mutex_lock(&pvt->lock);
746                 }
747         } while (res);
748         /* Then break the poll */
749         pthread_kill(pri->master, SIGURG);
750         return 0;
751 }
752 #endif
753
754 #define NUM_CADENCE_MAX 25
755 static int num_cadence = 4;
756 static int user_has_defined_cadences = 0;
757
758 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
759         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
760         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
761         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
762         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
763 };
764
765 int receivedRingT; /*!< Used to find out what ringtone we are on */
766
767 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
768  * is 1, the second pause is 2 and so on.
769  */
770
771 static int cidrings[NUM_CADENCE_MAX] = {
772         2,                                                                              /*!< Right after first long ring */
773         4,                                                                              /*!< Right after long part */
774         3,                                                                              /*!< After third chirp */
775         2,                                                                              /*!< Second spell */
776 };
777
778 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
779                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
780
781 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
782 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
783
784 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
785 {
786         int res;
787         if (p->subs[0].owner == ast)
788                 res = 0;
789         else if (p->subs[1].owner == ast)
790                 res = 1;
791         else if (p->subs[2].owner == ast)
792                 res = 2;
793         else {
794                 res = -1;
795                 if (!nullok)
796                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
797         }
798         return res;
799 }
800
801 #ifdef HAVE_LIBPRI
802 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
803 #else
804 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
805 #endif
806 {
807 #ifdef HAVE_LIBPRI
808         if (pri)
809                 ast_mutex_unlock(&pri->lock);
810 #endif                  
811         for (;;) {
812                 if (p->subs[a].owner) {
813                         if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
814                                 ast_mutex_unlock(&p->lock);
815                                 usleep(1);
816                                 ast_mutex_lock(&p->lock);
817                         } else {
818                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
819                                 ast_mutex_unlock(&p->subs[a].owner->lock);
820                                 break;
821                         }
822                 } else
823                         break;
824         }
825 #ifdef HAVE_LIBPRI
826         if (pri)
827                 ast_mutex_lock(&pri->lock);
828 #endif                  
829 }
830
831 #ifdef HAVE_LIBPRI
832 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
833 #else
834 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
835 #endif
836 {
837         /* We must unlock the PRI to avoid the possibility of a deadlock */
838 #ifdef HAVE_LIBPRI
839         if (pri)
840                 ast_mutex_unlock(&pri->lock);
841 #endif          
842         for (;;) {
843                 if (p->owner) {
844                         if (ast_mutex_trylock(&p->owner->lock)) {
845                                 ast_mutex_unlock(&p->lock);
846                                 usleep(1);
847                                 ast_mutex_lock(&p->lock);
848                         } else {
849                                 ast_queue_frame(p->owner, f);
850                                 ast_mutex_unlock(&p->owner->lock);
851                                 break;
852                         }
853                 } else
854                         break;
855         }
856 #ifdef HAVE_LIBPRI
857         if (pri)
858                 ast_mutex_lock(&pri->lock);
859 #endif          
860 }
861
862 static int restore_gains(struct zt_pvt *p);
863
864 static void swap_subs(struct zt_pvt *p, int a, int b)
865 {
866         int tchan;
867         int tinthreeway;
868         struct ast_channel *towner;
869
870         ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
871
872         tchan = p->subs[a].chan;
873         towner = p->subs[a].owner;
874         tinthreeway = p->subs[a].inthreeway;
875
876         p->subs[a].chan = p->subs[b].chan;
877         p->subs[a].owner = p->subs[b].owner;
878         p->subs[a].inthreeway = p->subs[b].inthreeway;
879
880         p->subs[b].chan = tchan;
881         p->subs[b].owner = towner;
882         p->subs[b].inthreeway = tinthreeway;
883
884         if (p->subs[a].owner) 
885                 p->subs[a].owner->fds[0] = p->subs[a].zfd;
886         if (p->subs[b].owner) 
887                 p->subs[b].owner->fds[0] = p->subs[b].zfd;
888         wakeup_sub(p, a, NULL);
889         wakeup_sub(p, b, NULL);
890 }
891
892 static int zt_open(char *fn)
893 {
894         int fd;
895         int isnum;
896         int chan = 0;
897         int bs;
898         int x;
899         isnum = 1;
900         for (x = 0; x < strlen(fn); x++) {
901                 if (!isdigit(fn[x])) {
902                         isnum = 0;
903                         break;
904                 }
905         }
906         if (isnum) {
907                 chan = atoi(fn);
908                 if (chan < 1) {
909                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
910                         return -1;
911                 }
912                 fn = "/dev/zap/channel";
913         }
914         fd = open(fn, O_RDWR | O_NONBLOCK);
915         if (fd < 0) {
916                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
917                 return -1;
918         }
919         if (chan) {
920                 if (ioctl(fd, ZT_SPECIFY, &chan)) {
921                         x = errno;
922                         close(fd);
923                         errno = x;
924                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
925                         return -1;
926                 }
927         }
928         bs = READ_SIZE;
929         if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
930         return fd;
931 }
932
933 static void zt_close(int fd)
934 {
935         if (fd > 0)
936                 close(fd);
937 }
938
939 static int zt_setlinear(int zfd, int linear)
940 {
941         int res;
942         res = ioctl(zfd, ZT_SETLINEAR, &linear);
943         if (res)
944                 return res;
945         return 0;
946 }
947
948
949 static int alloc_sub(struct zt_pvt *p, int x)
950 {
951         ZT_BUFFERINFO bi;
952         int res;
953         if (p->subs[x].zfd < 0) {
954                 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
955                 if (p->subs[x].zfd > -1) {
956                         res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
957                         if (!res) {
958                                 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
959                                 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
960                                 bi.numbufs = numbufs;
961                                 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
962                                 if (res < 0) {
963                                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
964                                 }
965                         } else 
966                                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
967                         if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
968                                 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
969                                 zt_close(p->subs[x].zfd);
970                                 p->subs[x].zfd = -1;
971                                 return -1;
972                         }
973                         if (option_debug)
974                                 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
975                         return 0;
976                 } else
977                         ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
978                 return -1;
979         }
980         ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
981         return -1;
982 }
983
984 static int unalloc_sub(struct zt_pvt *p, int x)
985 {
986         if (!x) {
987                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
988                 return -1;
989         }
990         ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
991         if (p->subs[x].zfd > -1) {
992                 zt_close(p->subs[x].zfd);
993         }
994         p->subs[x].zfd = -1;
995         p->subs[x].linear = 0;
996         p->subs[x].chan = 0;
997         p->subs[x].owner = NULL;
998         p->subs[x].inthreeway = 0;
999         p->polarity = POLARITY_IDLE;
1000         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
1001         return 0;
1002 }
1003
1004 static int zt_digit(struct ast_channel *ast, char digit)
1005 {
1006         ZT_DIAL_OPERATION zo;
1007         struct zt_pvt *p;
1008         int res = 0;
1009         int index;
1010         p = ast->tech_pvt;
1011         ast_mutex_lock(&p->lock);
1012         index = zt_get_index(ast, p, 0);
1013         if ((index == SUB_REAL) && p->owner) {
1014 #ifdef HAVE_LIBPRI
1015                 if ((p->sig == SIG_PRI) && (ast->_state == AST_STATE_DIALING) && !p->proceeding) {
1016                         if (p->setup_ack) {
1017                                 if (!pri_grab(p, p->pri)) {
1018                                         pri_information(p->pri->pri,p->call,digit);
1019                                         pri_rel(p->pri);
1020                                 } else
1021                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1022                         } else if (strlen(p->dialdest) < sizeof(p->dialdest) - 1) {
1023                                 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1024                                 res = strlen(p->dialdest);
1025                                 p->dialdest[res++] = digit;
1026                                 p->dialdest[res] = '\0';
1027                         }
1028                 } else {
1029 #else
1030                 {
1031 #endif
1032                         zo.op = ZT_DIAL_OP_APPEND;
1033                         zo.dialstr[0] = 'T';
1034                         zo.dialstr[1] = digit;
1035                         zo.dialstr[2] = 0;
1036                         if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1037                                 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1038                         else
1039                                 p->dialing = 1;
1040                 }
1041         }
1042         ast_mutex_unlock(&p->lock);
1043         return res;
1044 }
1045
1046 static char *events[] = {
1047         "No event",
1048         "On hook",
1049         "Ring/Answered",
1050         "Wink/Flash",
1051         "Alarm",
1052         "No more alarm",
1053         "HDLC Abort",
1054         "HDLC Overrun",
1055         "HDLC Bad FCS",
1056         "Dial Complete",
1057         "Ringer On",
1058         "Ringer Off",
1059         "Hook Transition Complete",
1060         "Bits Changed",
1061         "Pulse Start",
1062         "Timer Expired",
1063         "Timer Ping",
1064         "Polarity Reversal",
1065         "Ring Begin",
1066 };
1067
1068 static struct {
1069         int alarm;
1070         char *name;
1071 } alarms[] = {
1072         { ZT_ALARM_RED, "Red Alarm" },
1073         { ZT_ALARM_YELLOW, "Yellow Alarm" },
1074         { ZT_ALARM_BLUE, "Blue Alarm" },
1075         { ZT_ALARM_RECOVER, "Recovering" },
1076         { ZT_ALARM_LOOPBACK, "Loopback" },
1077         { ZT_ALARM_NOTOPEN, "Not Open" },
1078         { ZT_ALARM_NONE, "None" },
1079 };
1080
1081 static char *alarm2str(int alarm)
1082 {
1083         int x;
1084         for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1085                 if (alarms[x].alarm & alarm)
1086                         return alarms[x].name;
1087         }
1088         return alarm ? "Unknown Alarm" : "No Alarm";
1089 }
1090
1091 static char *event2str(int event)
1092 {
1093         static char buf[256];
1094         if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1095                 return events[event];
1096         sprintf(buf, "Event %d", event); /* safe */
1097         return buf;
1098 }
1099
1100 #ifdef HAVE_LIBPRI
1101 static char *dialplan2str(int dialplan)
1102 {
1103         if (dialplan == -1) {
1104                 return("Dynamically set dialplan in ISDN");
1105         }
1106         return (pri_plan2str(dialplan));
1107 }
1108 #endif
1109
1110 static char *zap_sig2str(int sig)
1111 {
1112         static char buf[256];
1113         switch (sig) {
1114         case SIG_EM:
1115                 return "E & M Immediate";
1116         case SIG_EMWINK:
1117                 return "E & M Wink";
1118         case SIG_EM_E1:
1119                 return "E & M E1";
1120         case SIG_FEATD:
1121                 return "Feature Group D (DTMF)";
1122         case SIG_FEATDMF:
1123                 return "Feature Group D (MF)";
1124         case SIG_FEATDMF_TA:
1125                 return "Feature Groud D (MF) Tandem Access";
1126         case SIG_FEATB:
1127                 return "Feature Group B (MF)";
1128         case SIG_E911:
1129                 return "E911 (MF)";
1130         case SIG_FGC_CAMA:
1131                 return "FGC/CAMA (Dialpulse)";
1132         case SIG_FGC_CAMAMF:
1133                 return "FGC/CAMA (MF)";
1134         case SIG_FXSLS:
1135                 return "FXS Loopstart";
1136         case SIG_FXSGS:
1137                 return "FXS Groundstart";
1138         case SIG_FXSKS:
1139                 return "FXS Kewlstart";
1140         case SIG_FXOLS:
1141                 return "FXO Loopstart";
1142         case SIG_FXOGS:
1143                 return "FXO Groundstart";
1144         case SIG_FXOKS:
1145                 return "FXO Kewlstart";
1146         case SIG_PRI:
1147                 return "PRI Signalling";
1148         case SIG_SF:
1149                 return "SF (Tone) Signalling Immediate";
1150         case SIG_SFWINK:
1151                 return "SF (Tone) Signalling Wink";
1152         case SIG_SF_FEATD:
1153                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1154         case SIG_SF_FEATDMF:
1155                 return "SF (Tone) Signalling with Feature Group D (MF)";
1156         case SIG_SF_FEATB:
1157                 return "SF (Tone) Signalling with Feature Group B (MF)";
1158         case SIG_GR303FXOKS:
1159                 return "GR-303 Signalling with FXOKS";
1160         case SIG_GR303FXSKS:
1161                 return "GR-303 Signalling with FXSKS";
1162         case 0:
1163                 return "Pseudo Signalling";
1164         default:
1165                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1166                 return buf;
1167         }
1168 }
1169
1170 #define sig2str zap_sig2str
1171
1172 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1173 {
1174         /* If the conference already exists, and we're already in it
1175            don't bother doing anything */
1176         ZT_CONFINFO zi;
1177         
1178         memset(&zi, 0, sizeof(zi));
1179         zi.chan = 0;
1180
1181         if (slavechannel > 0) {
1182                 /* If we have only one slave, do a digital mon */
1183                 zi.confmode = ZT_CONF_DIGITALMON;
1184                 zi.confno = slavechannel;
1185         } else {
1186                 if (!index) {
1187                         /* Real-side and pseudo-side both participate in conference */
1188                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1189                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1190                 } else
1191                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1192                 zi.confno = p->confno;
1193         }
1194         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1195                 return 0;
1196         if (c->zfd < 0)
1197                 return 0;
1198         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1199                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1200                 return -1;
1201         }
1202         if (slavechannel < 1) {
1203                 p->confno = zi.confno;
1204         }
1205         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1206         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1207         return 0;
1208 }
1209
1210 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1211 {
1212         /* If they're listening to our channel, they're ours */ 
1213         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1214                 return 1;
1215         /* If they're a talker on our (allocated) conference, they're ours */
1216         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1217                 return 1;
1218         return 0;
1219 }
1220
1221 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1222 {
1223         ZT_CONFINFO zi;
1224         if (/* Can't delete if there's no zfd */
1225                 (c->zfd < 0) ||
1226                 /* Don't delete from the conference if it's not our conference */
1227                 !isourconf(p, c)
1228                 /* Don't delete if we don't think it's conferenced at all (implied) */
1229                 ) return 0;
1230         memset(&zi, 0, sizeof(zi));
1231         zi.chan = 0;
1232         zi.confno = 0;
1233         zi.confmode = 0;
1234         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1235                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1236                 return -1;
1237         }
1238         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1239         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1240         return 0;
1241 }
1242
1243 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1244 {
1245         int x;
1246         int useslavenative;
1247         struct zt_pvt *slave = NULL;
1248         /* Start out optimistic */
1249         useslavenative = 1;
1250         /* Update conference state in a stateless fashion */
1251         for (x = 0; x < 3; x++) {
1252                 /* Any three-way calling makes slave native mode *definitely* out
1253                    of the question */
1254                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1255                         useslavenative = 0;
1256         }
1257         /* If we don't have any 3-way calls, check to see if we have
1258            precisely one slave */
1259         if (useslavenative) {
1260                 for (x = 0; x < MAX_SLAVES; x++) {
1261                         if (p->slaves[x]) {
1262                                 if (slave) {
1263                                         /* Whoops already have a slave!  No 
1264                                            slave native and stop right away */
1265                                         slave = NULL;
1266                                         useslavenative = 0;
1267                                         break;
1268                                 } else {
1269                                         /* We have one slave so far */
1270                                         slave = p->slaves[x];
1271                                 }
1272                         }
1273                 }
1274         }
1275         /* If no slave, slave native definitely out */
1276         if (!slave)
1277                 useslavenative = 0;
1278         else if (slave->law != p->law) {
1279                 useslavenative = 0;
1280                 slave = NULL;
1281         }
1282         if (out)
1283                 *out = slave;
1284         return useslavenative;
1285 }
1286
1287 static int reset_conf(struct zt_pvt *p)
1288 {
1289         ZT_CONFINFO zi;
1290         memset(&zi, 0, sizeof(zi));
1291         p->confno = -1;
1292         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1293         if (p->subs[SUB_REAL].zfd > -1) {
1294                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1295                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1296         }
1297         return 0;
1298 }
1299
1300 static int update_conf(struct zt_pvt *p)
1301 {
1302         int needconf = 0;
1303         int x;
1304         int useslavenative;
1305         struct zt_pvt *slave = NULL;
1306
1307         useslavenative = isslavenative(p, &slave);
1308         /* Start with the obvious, general stuff */
1309         for (x = 0; x < 3; x++) {
1310                 /* Look for three way calls */
1311                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1312                         conf_add(p, &p->subs[x], x, 0);
1313                         needconf++;
1314                 } else {
1315                         conf_del(p, &p->subs[x], x);
1316                 }
1317         }
1318         /* If we have a slave, add him to our conference now. or DAX
1319            if this is slave native */
1320         for (x = 0; x < MAX_SLAVES; x++) {
1321                 if (p->slaves[x]) {
1322                         if (useslavenative)
1323                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1324                         else {
1325                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1326                                 needconf++;
1327                         }
1328                 }
1329         }
1330         /* If we're supposed to be in there, do so now */
1331         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1332                 if (useslavenative)
1333                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1334                 else {
1335                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1336                         needconf++;
1337                 }
1338         }
1339         /* If we have a master, add ourselves to his conference */
1340         if (p->master) {
1341                 if (isslavenative(p->master, NULL)) {
1342                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1343                 } else {
1344                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1345                 }
1346         }
1347         if (!needconf) {
1348                 /* Nobody is left (or should be left) in our conference.
1349                    Kill it. */
1350                 p->confno = -1;
1351         }
1352         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1353         return 0;
1354 }
1355
1356 static void zt_enable_ec(struct zt_pvt *p)
1357 {
1358         int x;
1359         int res;
1360         if (!p)
1361                 return;
1362         if (p->echocanon) {
1363                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1364                 return;
1365         }
1366         if (p->digital) {
1367                 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1368                 return;
1369         }
1370         if (p->echocancel) {
1371                 if (p->sig == SIG_PRI) {
1372                         x = 1;
1373                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1374                         if (res)
1375                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1376                 }
1377                 x = p->echocancel;
1378                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1379                 if (res) 
1380                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1381                 else {
1382                         p->echocanon = 1;
1383                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1384                 }
1385         } else
1386                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1387 }
1388
1389 static void zt_train_ec(struct zt_pvt *p)
1390 {
1391         int x;
1392         int res;
1393         if (p && p->echocancel && p->echotraining) {
1394                 x = p->echotraining;
1395                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1396                 if (res)
1397                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1398                 else {
1399                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1400                 }
1401         } else
1402                 ast_log(LOG_DEBUG, "No echo training requested\n");
1403 }
1404
1405 static void zt_disable_ec(struct zt_pvt *p)
1406 {
1407         int x;
1408         int res;
1409         if (p->echocancel) {
1410                 x = 0;
1411                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1412                 if (res)
1413                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1414                 else
1415                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1416         }
1417         p->echocanon = 0;
1418 }
1419
1420 static void fill_txgain(struct zt_gains *g, float gain, int law)
1421 {
1422         int j;
1423         int k;
1424         float linear_gain = pow(10.0, gain / 20.0);
1425
1426         switch (law) {
1427         case ZT_LAW_ALAW:
1428                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1429                         if (gain) {
1430                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1431                                 if (k > 32767) k = 32767;
1432                                 if (k < -32767) k = -32767;
1433                                 g->txgain[j] = AST_LIN2A(k);
1434                         } else {
1435                                 g->txgain[j] = j;
1436                         }
1437                 }
1438                 break;
1439         case ZT_LAW_MULAW:
1440                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1441                         if (gain) {
1442                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1443                                 if (k > 32767) k = 32767;
1444                                 if (k < -32767) k = -32767;
1445                                 g->txgain[j] = AST_LIN2MU(k);
1446                         } else {
1447                                 g->txgain[j] = j;
1448                         }
1449                 }
1450                 break;
1451         }
1452 }
1453
1454 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1455 {
1456         int j;
1457         int k;
1458         float linear_gain = pow(10.0, gain / 20.0);
1459
1460         switch (law) {
1461         case ZT_LAW_ALAW:
1462                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1463                         if (gain) {
1464                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1465                                 if (k > 32767) k = 32767;
1466                                 if (k < -32767) k = -32767;
1467                                 g->rxgain[j] = AST_LIN2A(k);
1468                         } else {
1469                                 g->rxgain[j] = j;
1470                         }
1471                 }
1472                 break;
1473         case ZT_LAW_MULAW:
1474                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1475                         if (gain) {
1476                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1477                                 if (k > 32767) k = 32767;
1478                                 if (k < -32767) k = -32767;
1479                                 g->rxgain[j] = AST_LIN2MU(k);
1480                         } else {
1481                                 g->rxgain[j] = j;
1482                         }
1483                 }
1484                 break;
1485         }
1486 }
1487
1488 static int set_actual_txgain(int fd, int chan, float gain, int law)
1489 {
1490         struct zt_gains g;
1491         int res;
1492
1493         memset(&g, 0, sizeof(g));
1494         g.chan = chan;
1495         res = ioctl(fd, ZT_GETGAINS, &g);
1496         if (res) {
1497                 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1498                 return res;
1499         }
1500
1501         fill_txgain(&g, gain, law);
1502
1503         return ioctl(fd, ZT_SETGAINS, &g);
1504 }
1505
1506 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1507 {
1508         struct zt_gains g;
1509         int res;
1510
1511         memset(&g, 0, sizeof(g));
1512         g.chan = chan;
1513         res = ioctl(fd, ZT_GETGAINS, &g);
1514         if (res) {
1515                 ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1516                 return res;
1517         }
1518
1519         fill_rxgain(&g, gain, law);
1520
1521         return ioctl(fd, ZT_SETGAINS, &g);
1522 }
1523
1524 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1525 {
1526         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1527 }
1528
1529 static int bump_gains(struct zt_pvt *p)
1530 {
1531         int res;
1532
1533         /* Bump receive gain by 5.0db */
1534         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + 5.0, p->txgain, p->law);
1535         if (res) {
1536                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1537                 return -1;
1538         }
1539
1540         return 0;
1541 }
1542
1543 static int restore_gains(struct zt_pvt *p)
1544 {
1545         int res;
1546
1547         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1548         if (res) {
1549                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1550                 return -1;
1551         }
1552
1553         return 0;
1554 }
1555
1556 static inline int zt_set_hook(int fd, int hs)
1557 {
1558         int x, res;
1559         x = hs;
1560         res = ioctl(fd, ZT_HOOK, &x);
1561         if (res < 0) 
1562         {
1563                 if (errno == EINPROGRESS) return 0;
1564                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1565         }
1566         return res;
1567 }
1568
1569 static inline int zt_confmute(struct zt_pvt *p, int muted)
1570 {
1571         int x, y, res;
1572         x = muted;
1573         if (p->sig == SIG_PRI) {
1574                 y = 1;
1575                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1576                 if (res)
1577                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1578         }
1579         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1580         if (res < 0)
1581                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1582         return res;
1583 }
1584
1585 static int save_conference(struct zt_pvt *p)
1586 {
1587         struct zt_confinfo c;
1588         int res;
1589         if (p->saveconf.confmode) {
1590                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1591                 return -1;
1592         }
1593         p->saveconf.chan = 0;
1594         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1595         if (res) {
1596                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1597                 p->saveconf.confmode = 0;
1598                 return -1;
1599         }
1600         c.chan = 0;
1601         c.confno = 0;
1602         c.confmode = ZT_CONF_NORMAL;
1603         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1604         if (res) {
1605                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1606                 return -1;
1607         }
1608         if (option_debug)
1609                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1610         return 0;
1611 }
1612
1613 static int restore_conference(struct zt_pvt *p)
1614 {
1615         int res;
1616         if (p->saveconf.confmode) {
1617                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1618                 p->saveconf.confmode = 0;
1619                 if (res) {
1620                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1621                         return -1;
1622                 }
1623         }
1624         if (option_debug)
1625                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1626         return 0;
1627 }
1628
1629 static int send_callerid(struct zt_pvt *p);
1630
1631 static int send_cwcidspill(struct zt_pvt *p)
1632 {
1633         p->callwaitcas = 0;
1634         p->cidcwexpire = 0;
1635         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1636                 return -1;
1637         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1638         /* Make sure we account for the end */
1639         p->cidlen += READ_SIZE * 4;
1640         p->cidpos = 0;
1641         send_callerid(p);
1642         if (option_verbose > 2)
1643                 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1644         return 0;
1645 }
1646
1647 static int has_voicemail(struct zt_pvt *p)
1648 {
1649
1650         return ast_app_has_voicemail(p->mailbox, NULL);
1651 }
1652
1653 static int send_callerid(struct zt_pvt *p)
1654 {
1655         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1656         int res;
1657         /* Take out of linear mode if necessary */
1658         if (p->subs[SUB_REAL].linear) {
1659                 p->subs[SUB_REAL].linear = 0;
1660                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1661         }
1662         while (p->cidpos < p->cidlen) {
1663                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1664                 if (res < 0) {
1665                         if (errno == EAGAIN)
1666                                 return 0;
1667                         else {
1668                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1669                                 return -1;
1670                         }
1671                 }
1672                 if (!res)
1673                         return 0;
1674                 p->cidpos += res;
1675         }
1676         free(p->cidspill);
1677         p->cidspill = NULL;
1678         if (p->callwaitcas) {
1679                 /* Wait for CID/CW to expire */
1680                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1681         } else
1682                 restore_conference(p);
1683         return 0;
1684 }
1685
1686 static int zt_callwait(struct ast_channel *ast)
1687 {
1688         struct zt_pvt *p = ast->tech_pvt;
1689         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1690         if (p->cidspill) {
1691                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1692                 free(p->cidspill);
1693         }
1694         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1695                 return -1;
1696         save_conference(p);
1697         /* Silence */
1698         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1699         if (!p->callwaitrings && p->callwaitingcallerid) {
1700                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1701                 p->callwaitcas = 1;
1702                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1703         } else {
1704                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1705                 p->callwaitcas = 0;
1706                 p->cidlen = 2400 + READ_SIZE * 4;
1707         }
1708         p->cidpos = 0;
1709         send_callerid(p);
1710         
1711         return 0;
1712 }
1713
1714 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1715 {
1716         struct zt_pvt *p = ast->tech_pvt;
1717         int x, res, index,mysig;
1718         char *c, *n, *l;
1719 #ifdef HAVE_LIBPRI
1720         char *s = NULL;
1721 #endif
1722         char dest[256]; /* must be same length as p->dialdest */
1723         ast_mutex_lock(&p->lock);
1724         ast_copy_string(dest, rdest, sizeof(dest));
1725         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1726         if ((ast->_state == AST_STATE_BUSY)) {
1727                 p->subs[SUB_REAL].needbusy = 1;
1728                 ast_mutex_unlock(&p->lock);
1729                 return 0;
1730         }
1731         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1732                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1733                 ast_mutex_unlock(&p->lock);
1734                 return -1;
1735         }
1736         p->dialednone = 0;
1737         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
1738         {
1739                 /* Special pseudo -- automatically up */
1740                 ast_setstate(ast, AST_STATE_UP); 
1741                 ast_mutex_unlock(&p->lock);
1742                 return 0;
1743         }
1744         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1745         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1746         if (res)
1747                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1748         p->outgoing = 1;
1749
1750         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1751
1752         mysig = p->sig;
1753         if (p->outsigmod)
1754                 mysig = p->outsigmod;
1755
1756         switch (mysig) {
1757         case SIG_FXOLS:
1758         case SIG_FXOGS:
1759         case SIG_FXOKS:
1760                 if (p->owner == ast) {
1761                         /* Normal ring, on hook */
1762                         
1763                         /* Don't send audio while on hook, until the call is answered */
1764                         p->dialing = 1;
1765                         if (p->use_callerid) {
1766                                 /* Generate the Caller-ID spill if desired */
1767                                 if (p->cidspill) {
1768                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1769                                         free(p->cidspill);
1770                                 }
1771                                 p->callwaitcas = 0;
1772                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1773                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1774                                         p->cidpos = 0;
1775                                         send_callerid(p);
1776                                 }
1777                         }
1778                         /* Choose proper cadence */
1779                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1780                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
1781                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1782                                 p->cidrings = cidrings[p->distinctivering - 1];
1783                         } else {
1784                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1785                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1786                                 p->cidrings = p->sendcalleridafter;
1787                         }
1788
1789                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1790                         c = strchr(dest, '/');
1791                         if (c)
1792                                 c++;
1793                         if (c && (strlen(c) < p->stripmsd)) {
1794                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1795                                 c = NULL;
1796                         }
1797                         if (c) {
1798                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1799                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1800                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1801                         } else {
1802                                 p->dop.dialstr[0] = '\0';
1803                         }
1804                         x = ZT_RING;
1805                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1806                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1807                                 ast_mutex_unlock(&p->lock);
1808                                 return -1;
1809                         }
1810                         p->dialing = 1;
1811                 } else {
1812                         /* Call waiting call */
1813                         p->callwaitrings = 0;
1814                         if (ast->cid.cid_num)
1815                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1816                         else
1817                                 p->callwait_num[0] = '\0';
1818                         if (ast->cid.cid_name)
1819                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1820                         else
1821                                 p->callwait_name[0] = '\0';
1822                         /* Call waiting tone instead */
1823                         if (zt_callwait(ast)) {
1824                                 ast_mutex_unlock(&p->lock);
1825                                 return -1;
1826                         }
1827                         /* Make ring-back */
1828                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1829                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1830                                 
1831                 }
1832                 n = ast->cid.cid_name;
1833                 l = ast->cid.cid_num;
1834                 if (l)
1835                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1836                 else
1837                         p->lastcid_num[0] = '\0';
1838                 if (n)
1839                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1840                 else
1841                         p->lastcid_name[0] = '\0';
1842                 ast_setstate(ast, AST_STATE_RINGING);
1843                 index = zt_get_index(ast, p, 0);
1844                 if (index > -1) {
1845                         p->subs[index].needringing = 1;
1846                 }
1847                 break;
1848         case SIG_FXSLS:
1849         case SIG_FXSGS:
1850         case SIG_FXSKS:
1851         case SIG_EMWINK:
1852         case SIG_EM:
1853         case SIG_EM_E1:
1854         case SIG_FEATD:
1855         case SIG_FEATDMF:
1856         case SIG_E911:
1857         case SIG_FGC_CAMA:
1858         case SIG_FGC_CAMAMF:
1859         case SIG_FEATB:
1860         case SIG_SFWINK:
1861         case SIG_SF:
1862         case SIG_SF_FEATD:
1863         case SIG_SF_FEATDMF:
1864         case SIG_FEATDMF_TA:
1865         case SIG_SF_FEATB:
1866                 c = strchr(dest, '/');
1867                 if (c)
1868                         c++;
1869                 else
1870                         c = "";
1871                 if (strlen(c) < p->stripmsd) {
1872                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1873                         ast_mutex_unlock(&p->lock);
1874                         return -1;
1875                 }
1876 #ifdef HAVE_LIBPRI
1877                 /* Start the trunk, if not GR-303 */
1878                 if (!p->pri) {
1879 #endif
1880                         x = ZT_START;
1881                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1882                         if (res < 0) {
1883                                 if (errno != EINPROGRESS) {
1884                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1885                                         ast_mutex_unlock(&p->lock);
1886                                         return -1;
1887                                 }
1888                         }
1889 #ifdef HAVE_LIBPRI
1890                 }
1891 #endif
1892                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1893                 p->dop.op = ZT_DIAL_OP_REPLACE;
1894
1895                 c += p->stripmsd;
1896
1897                 switch (mysig) {
1898                 case SIG_FEATD:
1899                         l = ast->cid.cid_num;
1900                         if (l) 
1901                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1902                         else
1903                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1904                         break;
1905                 case SIG_FEATDMF:
1906                         l = ast->cid.cid_num;
1907                         if (l) 
1908                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1909                         else
1910                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1911                         break;
1912                 case SIG_FEATDMF_TA:
1913                 {
1914                         const char *cic, *ozz;
1915
1916                         /* If you have to go through a Tandem Access point you need to use this */
1917                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1918                         if (!ozz)
1919                                 ozz = defaultozz;
1920                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1921                         if (!cic)
1922                                 cic = defaultcic;
1923                         if (!ozz || !cic) {
1924                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1925                                 ast_mutex_unlock(&p->lock);
1926                                 return -1;
1927                         }
1928                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1929                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1930                         p->whichwink = 0;
1931                 }
1932                         break;
1933                 case SIG_E911:
1934                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1935                         break;
1936                 case SIG_FGC_CAMA:
1937                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
1938                         break;
1939                 case SIG_FGC_CAMAMF:
1940                 case SIG_FEATB:
1941                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
1942                         break;
1943                 default:
1944                         if (p->pulse)
1945                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
1946                         else
1947                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
1948                         break;
1949                 }
1950
1951                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1952                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1953                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1954                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1955                         p->echobreak = 1;
1956                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1957                 } else
1958                         p->echobreak = 0;
1959                 if (!res) {
1960                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1961                                 x = ZT_ONHOOK;
1962                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1963                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1964                                 ast_mutex_unlock(&p->lock);
1965                                 return -1;
1966                         }
1967                 } else
1968                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1969                 p->dialing = 1;
1970                 if (ast_strlen_zero(c))
1971                         p->dialednone = 1;
1972                 ast_setstate(ast, AST_STATE_DIALING);
1973                 break;
1974         case 0:
1975                 /* Special pseudo -- automatically up*/
1976                 ast_setstate(ast, AST_STATE_UP);
1977                 break;          
1978         case SIG_PRI:
1979                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1980                 p->dialdest[0] = '\0';
1981                 break;
1982         default:
1983                 ast_log(LOG_DEBUG, "not yet implemented\n");
1984                 ast_mutex_unlock(&p->lock);
1985                 return -1;
1986         }
1987 #ifdef HAVE_LIBPRI
1988         if (p->pri) {
1989                 struct pri_sr *sr;
1990 #ifdef SUPPORT_USERUSER
1991                 const char *useruser;
1992 #endif
1993                 int pridialplan;
1994                 int dp_strip;
1995                 int prilocaldialplan;
1996                 int ldp_strip;
1997                 int exclusive;
1998
1999                 c = strchr(dest, '/');
2000                 if (c)
2001                         c++;
2002                 else
2003                         c = dest;
2004                 if (!p->hidecallerid) {
2005                         l = ast->cid.cid_num;
2006                         n = ast->cid.cid_name;
2007                 } else {
2008                         l = NULL;
2009                         n = NULL;
2010                 }
2011                 if (strlen(c) < p->stripmsd) {
2012                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2013                         ast_mutex_unlock(&p->lock);
2014                         return -1;
2015                 }
2016                 if (mysig != SIG_FXSKS) {
2017                         p->dop.op = ZT_DIAL_OP_REPLACE;
2018                         s = strchr(c + p->stripmsd, 'w');
2019                         if (s) {
2020                                 if (strlen(s) > 1)
2021                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2022                                 else
2023                                         p->dop.dialstr[0] = '\0';
2024                                 *s = '\0';
2025                         } else {
2026                                 p->dop.dialstr[0] = '\0';
2027                         }
2028                 }
2029                 if (pri_grab(p, p->pri)) {
2030                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2031                         ast_mutex_unlock(&p->lock);
2032                         return -1;
2033                 }
2034                 if (!(p->call = pri_new_call(p->pri->pri))) {
2035                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2036                         pri_rel(p->pri);
2037                         ast_mutex_unlock(&p->lock);
2038                         return -1;
2039                 }
2040                 if (!(sr = pri_sr_new())) {
2041                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2042                         pri_rel(p->pri);
2043                         ast_mutex_unlock(&p->lock);
2044                 }
2045                 if (p->bearer || (mysig == SIG_FXSKS)) {
2046                         if (p->bearer) {
2047                                 ast_log(LOG_DEBUG, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
2048                                 p->bearer->call = p->call;
2049                         } else
2050                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2051                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2052                 }
2053                 p->digital = IS_DIGITAL(ast->transfercapability);
2054                 /* Add support for exclusive override */
2055                 if (p->priexclusive)
2056                         exclusive = 1;
2057                 else {
2058                 /* otherwise, traditional behavior */
2059                         if (p->pri->nodetype == PRI_NETWORK)
2060                                 exclusive = 0;
2061                         else
2062                                 exclusive = 1;
2063                 }
2064                 
2065                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2066                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2067                                         (p->digital ? -1 : 
2068                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2069                 if (p->pri->facilityenable)
2070                         pri_facility_enable(p->pri->pri);
2071
2072                 if (option_verbose > 2)
2073                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2074                 dp_strip = 0;
2075                 pridialplan = p->pri->dialplan - 1;
2076                 if (pridialplan == -2) { /* compute dynamically */
2077                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2078                                 dp_strip = strlen(p->pri->internationalprefix);
2079                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2080                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2081                                 dp_strip = strlen(p->pri->nationalprefix);
2082                                 pridialplan = PRI_NATIONAL_ISDN;
2083                         } else {
2084                                 pridialplan = PRI_LOCAL_ISDN;
2085                         }
2086                 }
2087                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2088
2089                 ldp_strip = 0;
2090                 prilocaldialplan = p->pri->localdialplan - 1;
2091                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2092                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2093                                 ldp_strip = strlen(p->pri->internationalprefix);
2094                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2095                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2096                                 ldp_strip = strlen(p->pri->nationalprefix);
2097                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2098                         } else {
2099                                 prilocaldialplan = PRI_LOCAL_ISDN;
2100                         }
2101                 }
2102                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2103                         p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2104                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
2105
2106 #ifdef SUPPORT_USERUSER
2107                 /* User-user info */
2108                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2109
2110                 if (useruser)
2111                         pri_sr_set_useruser(sr, useruser);
2112 #endif
2113
2114                 if (pri_setup(p->pri->pri, p->call, sr)) {
2115                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2116                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2117                         pri_rel(p->pri);
2118                         ast_mutex_unlock(&p->lock);
2119                         pri_sr_free(sr);
2120                         return -1;
2121                 }
2122                 pri_sr_free(sr);
2123                 ast_setstate(ast, AST_STATE_DIALING);
2124                 pri_rel(p->pri);
2125         }
2126 #endif          
2127         ast_mutex_unlock(&p->lock);
2128         return 0;
2129 }
2130
2131 static void destroy_zt_pvt(struct zt_pvt **pvt)
2132 {
2133         struct zt_pvt *p = *pvt;
2134         /* Remove channel from the list */
2135         if (p->prev)
2136                 p->prev->next = p->next;
2137         if (p->next)
2138                 p->next->prev = p->prev;
2139         if (p->use_smdi)
2140                 ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
2141         ast_mutex_destroy(&p->lock);
2142         free(p);
2143         *pvt = NULL;
2144 }
2145
2146 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2147 {
2148         int owned = 0;
2149         int i = 0;
2150
2151         if (!now) {
2152                 if (cur->owner) {
2153                         owned = 1;
2154                 }
2155
2156                 for (i = 0; i < 3; i++) {
2157                         if (cur->subs[i].owner) {
2158                                 owned = 1;
2159                         }
2160                 }
2161                 if (!owned) {
2162                         if (prev) {
2163                                 prev->next = cur->next;
2164                                 if (prev->next)
2165                                         prev->next->prev = prev;
2166                                 else
2167                                         ifend = prev;
2168                         } else {
2169                                 iflist = cur->next;
2170                                 if (iflist)
2171                                         iflist->prev = NULL;
2172                                 else
2173                                         ifend = NULL;
2174                         }
2175                         if (cur->subs[SUB_REAL].zfd > -1) {
2176                                 zt_close(cur->subs[SUB_REAL].zfd);
2177                         }
2178                         destroy_zt_pvt(&cur);
2179                 }
2180         } else {
2181                 if (prev) {
2182                         prev->next = cur->next;
2183                         if (prev->next)
2184                                 prev->next->prev = prev;
2185                         else
2186                                 ifend = prev;
2187                 } else {
2188                         iflist = cur->next;
2189                         if (iflist)
2190                                 iflist->prev = NULL;
2191                         else
2192                                 ifend = NULL;
2193                 }
2194                 if (cur->subs[SUB_REAL].zfd > -1) {
2195                         zt_close(cur->subs[SUB_REAL].zfd);
2196                 }
2197                 destroy_zt_pvt(&cur);
2198         }
2199         return 0;
2200 }
2201
2202 #ifdef HAVE_LIBPRI
2203 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2204
2205 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2206
2207 static char *zap_send_keypad_facility_descrip = 
2208 "  ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2209 "  IE over the current channel.\n";
2210
2211 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2212 {
2213         /* Data will be our digit string */
2214         struct zt_pvt *p;
2215         char *digits = (char *) data;
2216
2217         if (ast_strlen_zero(digits)) {
2218                 ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2219                 return -1;
2220         }
2221
2222         p = (struct zt_pvt *)chan->tech_pvt;
2223
2224         if (!p) {
2225                 ast_log(LOG_DEBUG, "Unable to find technology private\n");
2226                 return -1;
2227         }
2228
2229         ast_mutex_lock(&p->lock);
2230
2231         if (!p->pri || !p->call) {
2232                 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2233                 ast_mutex_unlock(&p->lock);
2234                 return -1;
2235         }
2236
2237         if (!pri_grab(p, p->pri)) {
2238                 pri_keypad_facility(p->pri->pri, p->call, digits);
2239                 pri_rel(p->pri);
2240         } else {
2241                 ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2242                 ast_mutex_unlock(&p->lock);
2243                 return -1;
2244         }
2245
2246         ast_mutex_unlock(&p->lock);
2247
2248         return 0;
2249 }
2250
2251 static int pri_is_up(struct zt_pri *pri)
2252 {
2253         int x;
2254         for (x = 0; x < NUM_DCHANS; x++) {
2255                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2256                         return 1;
2257         }
2258         return 0;
2259 }
2260
2261 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2262 {
2263         bearer->owner = &inuse;
2264         bearer->realcall = crv;
2265         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2266         if (crv->subs[SUB_REAL].owner)
2267                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2268         crv->bearer = bearer;
2269         crv->call = bearer->call;
2270         crv->pri = pri;
2271         return 0;
2272 }
2273
2274 static char *pri_order(int level)
2275 {
2276         switch (level) {
2277         case 0:
2278                 return "Primary";
2279         case 1:
2280                 return "Secondary";
2281         case 2:
2282                 return "Tertiary";
2283         case 3:
2284                 return "Quaternary";
2285         default:
2286                 return "<Unknown>";
2287         }               
2288 }
2289
2290 /* Returns fd of the active dchan */
2291 static int pri_active_dchan_fd(struct zt_pri *pri)
2292 {
2293         int x = -1;
2294
2295         for (x = 0; x < NUM_DCHANS; x++) {
2296                 if ((pri->dchans[x] == pri->pri))
2297                         break;
2298         }
2299
2300         return pri->fds[x];
2301 }
2302
2303 static int pri_find_dchan(struct zt_pri *pri)
2304 {
2305         int oldslot = -1;
2306         struct pri *old;
2307         int newslot = -1;
2308         int x;
2309         old = pri->pri;
2310         for (x = 0; x < NUM_DCHANS; x++) {
2311                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2312                         newslot = x;
2313                 if (pri->dchans[x] == old) {
2314                         oldslot = x;
2315                 }
2316         }
2317         if (newslot < 0) {
2318                 newslot = 0;
2319                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2320                         pri->dchannels[newslot]);
2321         }
2322         if (old && (oldslot != newslot))
2323                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2324                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2325         pri->pri = pri->dchans[newslot];
2326         return 0;
2327 }
2328 #endif
2329
2330 static int zt_hangup(struct ast_channel *ast)
2331 {
2332         int res;
2333         int index,x, law;
2334         /*static int restore_gains(struct zt_pvt *p);*/
2335         struct zt_pvt *p = ast->tech_pvt;
2336         struct zt_pvt *tmp = NULL;
2337         struct zt_pvt *prev = NULL;
2338         ZT_PARAMS par;
2339
2340         if (option_debug)
2341                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2342         if (!ast->tech_pvt) {
2343                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2344                 return 0;
2345         }
2346         
2347         ast_mutex_lock(&p->lock);
2348         
2349         index = zt_get_index(ast, p, 1);
2350
2351         if (p->sig == SIG_PRI) {
2352                 x = 1;
2353                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2354         }
2355
2356         x = 0;
2357         zt_confmute(p, 0);
2358         restore_gains(p);
2359         if (p->origcid_num) {
2360                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2361                 free(p->origcid_num);
2362                 p->origcid_num = NULL;
2363         }       
2364         if (p->origcid_name) {
2365                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2366                 free(p->origcid_name);
2367                 p->origcid_name = NULL;
2368         }       
2369         if (p->dsp)
2370                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2371         if (p->exten)
2372                 p->exten[0] = '\0';
2373
2374         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2375                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2376         p->ignoredtmf = 0;
2377         
2378         if (index > -1) {
2379                 /* Real channel, do some fixup */
2380                 p->subs[index].owner = NULL;
2381                 p->subs[index].needanswer = 0;
2382                 p->subs[index].needflash = 0;
2383                 p->subs[index].needringing = 0;
2384                 p->subs[index].needbusy = 0;
2385                 p->subs[index].needcongestion = 0;
2386                 p->subs[index].linear = 0;
2387                 p->subs[index].needcallerid = 0;
2388                 p->polarity = POLARITY_IDLE;
2389                 zt_setlinear(p->subs[index].zfd, 0);
2390                 if (index == SUB_REAL) {
2391                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2392                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2393                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2394                                         /* We had flipped over to answer a callwait and now it's gone */
2395                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2396                                         /* Move to the call-wait, but un-own us until they flip back. */
2397                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2398                                         unalloc_sub(p, SUB_CALLWAIT);
2399                                         p->owner = NULL;
2400                                 } else {
2401                                         /* The three way hung up, but we still have a call wait */
2402                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2403                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2404                                         unalloc_sub(p, SUB_THREEWAY);
2405                                         if (p->subs[SUB_REAL].inthreeway) {
2406                                                 /* This was part of a three way call.  Immediately make way for
2407                                                    another call */
2408                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2409                                                 p->owner = p->subs[SUB_REAL].owner;
2410                                         } else {
2411                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2412                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2413                                                 p->owner = NULL;
2414                                         }
2415                                         p->subs[SUB_REAL].inthreeway = 0;
2416                                 }
2417                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2418                                 /* Move to the call-wait and switch back to them. */
2419                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2420                                 unalloc_sub(p, SUB_CALLWAIT);
2421                                 p->owner = p->subs[SUB_REAL].owner;
2422                                 if (p->owner->_state != AST_STATE_UP)
2423                                         p->subs[SUB_REAL].needanswer = 1;
2424                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2425                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2426                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2427                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2428                                 unalloc_sub(p, SUB_THREEWAY);
2429                                 if (p->subs[SUB_REAL].inthreeway) {
2430                                         /* This was part of a three way call.  Immediately make way for
2431                                            another call */
2432                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2433                                         p->owner = p->subs[SUB_REAL].owner;
2434                                 } else {
2435                                         /* This call hasn't been completed yet...  Set owner to NULL */
2436                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2437                                         p->owner = NULL;
2438                                 }
2439                                 p->subs[SUB_REAL].inthreeway = 0;
2440                         }
2441                 } else if (index == SUB_CALLWAIT) {
2442                         /* Ditch the holding callwait call, and immediately make it availabe */
2443                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2444                                 /* This is actually part of a three way, placed on hold.  Place the third part
2445                                    on music on hold now */
2446                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2447                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2448                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2449                                 /* Make it the call wait now */
2450                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2451                                 unalloc_sub(p, SUB_THREEWAY);
2452                         } else
2453                                 unalloc_sub(p, SUB_CALLWAIT);
2454                 } else if (index == SUB_THREEWAY) {
2455                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2456                                 /* The other party of the three way call is currently in a call-wait state.
2457                                    Start music on hold for them, and take the main guy out of the third call */
2458                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2459                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2460                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2461                         }
2462                         p->subs[SUB_REAL].inthreeway = 0;
2463                         /* If this was part of a three way call index, let us make
2464                            another three way call */
2465                         unalloc_sub(p, SUB_THREEWAY);
2466                 } else {
2467                         /* This wasn't any sort of call, but how are we an index? */
2468                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2469                 }
2470         }
2471
2472         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2473                 p->owner = NULL;
2474                 p->ringt = 0;
2475                 p->distinctivering = 0;
2476                 p->confirmanswer = 0;
2477                 p->cidrings = 1;
2478                 p->outgoing = 0;
2479                 p->digital = 0;
2480                 p->faxhandled = 0;
2481                 p->pulsedial = 0;
2482                 p->onhooktime = time(NULL);
2483 #ifdef HAVE_LIBPRI
2484                 p->proceeding = 0;
2485                 p->progress = 0;
2486                 p->alerting = 0;
2487                 p->setup_ack = 0;
2488 #endif          
2489                 if (p->dsp) {
2490                         ast_dsp_free(p->dsp);
2491                         p->dsp = NULL;
2492                 }
2493
2494                 law = ZT_LAW_DEFAULT;
2495                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2496                 if (res < 0) 
2497                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2498                 /* Perform low level hangup if no owner left */
2499 #ifdef HAVE_LIBPRI
2500                 if (p->pri) {
2501 #ifdef SUPPORT_USERUSER
2502                         const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2503 #endif
2504
2505                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2506                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2507                                 if (!pri_grab(p, p->pri)) {
2508                                         if (p->alreadyhungup) {
2509                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2510
2511 #ifdef SUPPORT_USERUSER
2512                                                 pri_call_set_useruser(p->call, useruser);
2513 #endif
2514
2515                                                 pri_hangup(p->pri->pri, p->call, -1);
2516                                                 p->call = NULL;
2517                                                 if (p->bearer) 
2518                                                         p->bearer->call = NULL;
2519                                         } else {
2520                                                 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2521                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2522                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2523
2524 #ifdef SUPPORT_USERUSER
2525                                                 pri_call_set_useruser(p->call, useruser);
2526 #endif
2527
2528                                                 p->alreadyhungup = 1;
2529                                                 if (p->bearer)
2530                                                         p->bearer->alreadyhungup = 1;
2531                                                 if (cause) {
2532                                                         if (atoi(cause))
2533                                                                 icause = atoi(cause);
2534                                                 }
2535                                                 pri_hangup(p->pri->pri, p->call, icause);
2536                                         }
2537                                         if (res < 0) 
2538                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2539                                         pri_rel(p->pri);                        
2540                                 } else {
2541                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2542                                         res = -1;
2543                                 }
2544                         } else {
2545                                 if (p->bearer)
2546                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2547                                 p->call = NULL;
2548                                 res = 0;
2549                         }
2550                 }
2551 #endif
2552                 if (p->sig && (p->sig != SIG_PRI))
2553                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2554                 if (res < 0) {
2555                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2556                 }
2557                 switch (p->sig) {
2558                 case SIG_FXOGS:
2559                 case SIG_FXOLS:
2560                 case SIG_FXOKS:
2561                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2562                         if (!res) {
2563 #if 0
2564                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2565 #endif
2566                                 /* If they're off hook, try playing congestion */
2567                                 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
2568                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2569                                 else
2570                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2571                         }
2572                         break;
2573                 case SIG_FXSGS:
2574                 case SIG_FXSLS:
2575                 case SIG_FXSKS:
2576                         /* Make sure we're not made available for at least two seconds assuming
2577                            we were actually used for an inbound or outbound call. */
2578                         if (ast->_state != AST_STATE_RESERVED) {
2579                                 time(&p->guardtime);
2580                                 p->guardtime += 2;
2581                         }
2582                         break;
2583                 default:
2584                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2585                 }
2586                 if (p->cidspill)
2587                         free(p->cidspill);
2588                 if (p->sig)
2589                         zt_disable_ec(p);
2590                 x = 0;
2591                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2592                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2593                 p->didtdd = 0;
2594                 p->cidspill = NULL;
2595                 p->callwaitcas = 0;
2596                 p->callwaiting = p->permcallwaiting;
2597                 p->hidecallerid = p->permhidecallerid;
2598                 p->dialing = 0;
2599                 p->rdnis[0] = '\0';
2600                 update_conf(p);
2601                 reset_conf(p);
2602                 /* Restore data mode */
2603                 if (p->sig == SIG_PRI) {
2604                         x = 0;
2605                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2606                 }
2607 #ifdef HAVE_LIBPRI
2608                 if (p->bearer) {
2609                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2610                         /* Free up the bearer channel as well, and
2611                            don't use its file descriptor anymore */
2612                         update_conf(p->bearer);
2613                         reset_conf(p->bearer);
2614                         p->bearer->owner = NULL;
2615                         p->bearer->realcall = NULL;
2616                         p->bearer = NULL;
2617                         p->subs[SUB_REAL].zfd = -1;
2618                         p->pri = NULL;
2619                 }
2620 #endif
2621                 restart_monitor();
2622         }
2623
2624         p->callwaitingrepeat = 0;
2625         p->cidcwexpire = 0;
2626         p->oprmode = 0;
2627         ast->tech_pvt = NULL;
2628         ast_mutex_unlock(&p->lock);
2629         ast_mutex_lock(&usecnt_lock);
2630         usecnt--;
2631         if (usecnt < 0) 
2632                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2633         ast_mutex_unlock(&usecnt_lock);
2634         ast_update_use_count();
2635         if (option_verbose > 2) 
2636                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2637
2638         ast_mutex_lock(&iflock);
2639         tmp = iflist;
2640         prev = NULL;
2641         if (p->destroy) {
2642                 while (tmp) {
2643                         if (tmp == p) {
2644                                 destroy_channel(prev, tmp, 0);
2645                                 break;
2646                         } else {
2647                                 prev = tmp;
2648                                 tmp = tmp->next;
2649                         }
2650                 }
2651         }
2652         ast_mutex_unlock(&iflock);
2653         return 0;
2654 }
2655
2656 static int zt_answer(struct ast_channel *ast)
2657 {
2658         struct zt_pvt *p = ast->tech_pvt;
2659         int res = 0;
2660         int index;
2661         int oldstate = ast->_state;
2662         ast_setstate(ast, AST_STATE_UP);
2663         ast_mutex_lock(&p->lock);
2664         index = zt_get_index(ast, p, 0);
2665         if (index < 0)
2666                 index = SUB_REAL;
2667         /* nothing to do if a radio channel */
2668         if ((p->radio || (p->oprmode < 0))) {
2669                 ast_mutex_unlock(&p->lock);
2670                 return 0;
2671         }
2672         switch (p->sig) {
2673         case SIG_FXSLS:
2674         case SIG_FXSGS:
2675         case SIG_FXSKS:
2676                 p->ringt = 0;
2677                 /* Fall through */
2678         case SIG_EM:
2679         case SIG_EM_E1:
2680         case SIG_EMWINK:
2681         case SIG_FEATD:
2682         case SIG_FEATDMF:
2683         case SIG_FEATDMF_TA:
2684         case SIG_E911:
2685         case SIG_FGC_CAMA:
2686         case SIG_FGC_CAMAMF:
2687         case SIG_FEATB:
2688         case SIG_SF:
2689         case SIG_SFWINK:
2690         case SIG_SF_FEATD:
2691         case SIG_SF_FEATDMF:
2692         case SIG_SF_FEATB:
2693         case SIG_FXOLS:
2694         case SIG_FXOGS:
2695         case SIG_FXOKS:
2696                 /* Pick up the line */
2697                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2698                 if (p->hanguponpolarityswitch) {
2699                         gettimeofday(&p->polaritydelaytv, NULL);
2700                 }
2701                 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2702                 tone_zone_play_tone(p->subs[index].zfd, -1);
2703                 p->dialing = 0;
2704                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2705                         if (oldstate == AST_STATE_RINGING) {
2706                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2707                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2708                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2709                                 p->owner = p->subs[SUB_REAL].owner;
2710                         }
2711                 }
2712                 if (p->sig & __ZT_SIG_FXS) {
2713                         zt_enable_ec(p);
2714                         zt_train_ec(p);
2715                 }
2716                 break;
2717 #ifdef HAVE_LIBPRI
2718         case SIG_PRI:
2719                 /* Send a pri acknowledge */
2720                 if (!pri_grab(p, p->pri)) {
2721                         p->proceeding = 1;
2722                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2723                         pri_rel(p->pri);
2724                 } else {
2725                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2726                         res = -1;
2727                 }
2728                 break;
2729 #endif
2730         case 0:
2731                 ast_mutex_unlock(&p->lock);
2732                 return 0;
2733         default:
2734                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2735                 res = -1;
2736         }
2737         ast_mutex_unlock(&p->lock);
2738         return res;
2739 }
2740
2741 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2742 {
2743         char *cp;
2744         signed char *scp;
2745         int x;
2746         int index;
2747         struct zt_pvt *p = chan->tech_pvt, *pp;
2748         struct oprmode *oprmode;
2749         
2750
2751         /* all supported options require data */
2752         if (!data || (datalen < 1)) {
2753                 errno = EINVAL;
2754                 return -1;
2755         }
2756
2757         switch (option) {
2758         case AST_OPTION_TXGAIN:
2759                 scp = (signed char *) data;
2760                 index = zt_get_index(chan, p, 0);
2761                 if (index < 0) {
2762                         ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2763                         return -1;
2764                 }
2765                 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2766                 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2767         case AST_OPTION_RXGAIN:
2768                 scp = (signed char *) data;
2769                 index = zt_get_index(chan, p, 0);
2770                 if (index < 0) {
2771                         ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2772                         return -1;
2773                 }
2774                 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2775                 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2776         case AST_OPTION_TONE_VERIFY:
2777                 if (!p->dsp)
2778                         break;
2779                 cp = (char *) data;
2780                 switch (*cp) {
2781                 case 1:
2782                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2783                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2784                         break;
2785                 case 2:
2786                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2787                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2788                         break;
2789                 default:
2790                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2791                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2792                         break;
2793                 }
2794                 break;
2795         case AST_OPTION_TDD:
2796                 /* turn on or off TDD */
2797                 cp = (char *) data;
2798                 p->mate = 0;
2799                 if (!*cp) { /* turn it off */
2800                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2801                         if (p->tdd)
2802                                 tdd_free(p->tdd);
2803                         p->tdd = 0;
2804                         break;
2805                 }
2806                 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2807                         (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2808                 zt_disable_ec(p);
2809                 /* otherwise, turn it on */
2810                 if (!p->didtdd) { /* if havent done it yet */
2811                         unsigned char mybuf[41000], *buf;
2812                         int size, res, fd, len;
2813                         struct pollfd fds[1];
2814
2815                         buf = mybuf;
2816                         memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2817                         ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
2818                         len = 40000;
2819                         index = zt_get_index(chan, p, 0);
2820                         if (index < 0) {
2821                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2822                                 return -1;
2823                         }
2824                         fd = p->subs[index].zfd;
2825                         while (len) {
2826                                 if (ast_check_hangup(chan))
2827                                         return -1;
2828                                 size = len;
2829                                 if (size > READ_SIZE)
2830                                         size = READ_SIZE;
2831                                 fds[0].fd = fd;
2832                                 fds[0].events = POLLPRI | POLLOUT;
2833                                 fds[0].revents = 0;
2834                                 res = poll(fds, 1, -1);
2835                                 if (!res) {
2836                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2837                                         continue;
2838                                 }
2839                                 /* if got exception */
2840                                 if (fds[0].revents & POLLPRI)
2841                                         return -1;
2842                                 if (!(fds[0].revents & POLLOUT)) {
2843                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2844                                         continue;
2845                                 }
2846                                 res = write(fd, buf, size);
2847                                 if (res != size) {
2848                                         if (res == -1) return -1;
2849                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2850                                         break;
2851                                 }
2852                                 len -= size;
2853                                 buf += size;
2854                         }
2855                         p->didtdd = 1; /* set to have done it now */            
2856                 }
2857                 if (*cp == 2) { /* Mate mode */
2858                         if (p->tdd)
2859                                 tdd_free(p->tdd);
2860                         p->tdd = 0;
2861                         p->mate = 1;
2862                         break;
2863                 }               
2864                 if (!p->tdd) { /* if we dont have one yet */
2865                         p->tdd = tdd_new(); /* allocate one */
2866                 }               
2867                 break;
2868         case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2869                 if (!p->dsp)
2870                         break;
2871                 cp = (char *) data;
2872                 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2873                         *cp ? "ON" : "OFF", (int) *cp, chan->name);
2874                 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
2875                 break;
2876         case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2877                 cp = (char *) data;
2878                 if (!*cp) {             
2879                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2880                         x = 0;
2881                         zt_disable_ec(p);
2882                 } else {                
2883                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2884                         x = 1;
2885                 }
2886                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2887                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2888                 break;
2889         case AST_OPTION_OPRMODE:  /* Operator services mode */
2890                 oprmode = (struct oprmode *) data;
2891                 pp = oprmode->peer->tech_pvt;
2892                 p->oprmode = pp->oprmode = 0;
2893                 /* setup peers */
2894                 p->oprpeer = pp;
2895                 pp->oprpeer = p;
2896                 /* setup modes, if any */
2897                 if (oprmode->mode) 
2898                 {
2899                         pp->oprmode = oprmode->mode;
2900                         p->oprmode = -oprmode->mode;
2901                 }
2902                 ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
2903                         oprmode->mode, chan->name,oprmode->peer->name);;
2904                 break;
2905         case AST_OPTION_ECHOCAN:
2906                 cp = (char *) data;
2907                 if (*cp) {
2908                         ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
2909                         zt_enable_ec(p);
2910                 } else {
2911                         ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
2912                         zt_disable_ec(p);
2913                 }
2914                 break;
2915         }
2916         errno = 0;
2917
2918         return 0;
2919 }
2920
2921 static int zt_func_read(struct ast_channel *chan, char *function, char *data, char *buf, size_t len)
2922 {
2923         struct zt_pvt *p = chan->tech_pvt;
2924         
2925         if (!strcasecmp(data, "rxgain")) {
2926                 ast_mutex_lock(&p->lock);
2927                 snprintf(buf, len, "%f", p->rxgain);
2928                 ast_mutex_unlock(&p->lock);     
2929         } else if (!strcasecmp(data, "txgain")) {
2930                 ast_mutex_lock(&p->lock);
2931                 snprintf(buf, len, "%f", p->txgain);
2932                 ast_mutex_unlock(&p->lock);     
2933         } else {
2934                 ast_copy_string(buf, "", len);
2935         }
2936         return 0;
2937 }
2938
2939
2940 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2941 {
2942         /* Unlink a specific slave or all slaves/masters from a given master */
2943         int x;
2944         int hasslaves;
2945         if (!master)
2946                 return;
2947         if (needlock) {
2948                 ast_mutex_lock(&master->lock);
2949                 if (slave) {
2950                         while (ast_mutex_trylock(&slave->lock)) {
2951                                 ast_mutex_unlock(&master->lock);
2952                                 usleep(1);
2953                                 ast_mutex_lock(&master->lock);
2954                         }
2955                 }
2956         }
2957         hasslaves = 0;
2958         for (x = 0; x < MAX_SLAVES; x++) {
2959                 if (master->slaves[x]) {
2960                         if (!slave || (master->slaves[x] == slave)) {
2961                                 /* Take slave out of the conference */
2962                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2963                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2964                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2965                                 master->slaves[x]->master = NULL;
2966                                 master->slaves[x] = NULL;
2967                         } else
2968                                 hasslaves = 1;
2969                 }
2970                 if (!hasslaves)
2971                         master->inconference = 0;
2972         }
2973         if (!slave) {
2974                 if (master->master) {
2975                         /* Take master out of the conference */
2976                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2977                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2978                         hasslaves = 0;
2979                         for (x = 0; x < MAX_SLAVES; x++) {
2980                                 if (master->master->slaves[x] == master)
2981                                         master->master->slaves[x] = NULL;
2982                                 else if (master->master->slaves[x])
2983                                         hasslaves = 1;
2984                         }
2985                         if (!hasslaves)
2986                                 master->master->inconference = 0;
2987                 }
2988                 master->master = NULL;
2989         }
2990         update_conf(master);
2991         if (needlock) {
2992                 if (slave)
2993                         ast_mutex_unlock(&slave->lock);
2994                 ast_mutex_unlock(&master->lock);
2995         }
2996 }
2997
2998 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2999         int x;
3000         if (!slave || !master) {
3001                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
3002                 return;
3003         }
3004         for (x = 0; x < MAX_SLAVES; x++) {
3005                 if (!master->slaves[x]) {
3006                         master->slaves[x] = slave;
3007                         break;
3008                 }
3009         }
3010         if (x >= MAX_SLAVES) {
3011                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
3012                 master->slaves[MAX_SLAVES - 1] = slave;
3013         }
3014         if (slave->master) 
3015                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
3016         slave->master = master;
3017         
3018         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
3019 }
3020
3021 static void disable_dtmf_detect(struct zt_pvt *p)
3022 {
3023 #ifdef ZT_TONEDETECT
3024         int val;
3025 #endif
3026
3027         p->ignoredtmf = 1;
3028
3029 #ifdef ZT_TONEDETECT
3030         val = 0;
3031         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3032 #endif          
3033         if (!p->hardwaredtmf && p->dsp) {
3034                 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3035                 ast_dsp_set_features(p->dsp, p->dsp_features);
3036         }
3037 }
3038
3039 static void enable_dtmf_detect(struct zt_pvt *p)
3040 {
3041 #ifdef ZT_TONEDETECT
3042         int val;
3043 #endif
3044
3045         if (p->channel == CHAN_PSEUDO)
3046                 return;
3047
3048         p->ignoredtmf = 0;
3049
3050 #ifdef ZT_TONEDETECT
3051         val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3052         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3053 #endif          
3054         if (!p->hardwaredtmf && p->dsp) {
3055                 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3056                 ast_dsp_set_features(p->dsp, p->dsp_features);
3057         }
3058 }
3059
3060 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3061 {
3062         struct ast_channel *who;
3063         struct zt_pvt *p0, *p1, *op0, *op1;
3064         struct zt_pvt *master = NULL, *slave = NULL;
3065         struct ast_frame *f;
3066         int inconf = 0;
3067         int nothingok = 1;
3068         int ofd0, ofd1;
3069         int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
3070         int os0 = -1, os1 = -1;
3071         int priority = 0;
3072         struct ast_channel *oc0, *oc1;
3073         enum ast_bridge_result res;
3074
3075 #ifdef PRI_2BCT
3076         int triedtopribridge = 0;
3077         q931_call *q931c0 = NULL, *q931c1 = NULL;
3078 #endif
3079
3080         /* For now, don't attempt to native bridge if either channel needs DTMF detection.
3081            There is code below to handle it properly until DTMF is actually seen,
3082            but due to currently unresolved issues it's ignored...
3083         */
3084
3085         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
3086                 return AST_BRIDGE_FAILED_NOWARN;
3087
3088         ast_mutex_lock(&c0->lock);
3089         ast_mutex_lock(&c1->lock);
3090
3091         p0 = c0->tech_pvt;
3092         p1 = c1->tech_pvt;
3093         /* cant do pseudo-channels here */
3094         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
3095                 ast_mutex_unlock(&c0->lock);
3096                 ast_mutex_unlock(&c1->lock);
3097                 return AST_BRIDGE_FAILED_NOWARN;
3098         }
3099
3100         oi0 = zt_get_index(c0, p0, 0);
3101         oi1 = zt_get_index(c1, p1, 0);
3102         if ((oi0 < 0) || (oi1 < 0)) {
3103                 ast_mutex_unlock(&c0->lock);
3104                 ast_mutex_unlock(&c1->lock);
3105                 return AST_BRIDGE_FAILED;
3106         }
3107
3108         op0 = p0 = c0->tech_pvt;
3109         op1 = p1 = c1->tech_pvt;
3110         ofd0 = c0->fds[0];
3111         ofd1 = c1->fds[0];
3112         oc0 = p0->owner;
3113         oc1 = p1->owner;
3114
3115         ast_mutex_lock(&p0->lock);
3116         if (ast_mutex_trylock(&p1->lock)) {
3117                 /* Don't block, due to potential for deadlock */
3118                 ast_mutex_unlock(&p0->lock);
3119                 ast_mutex_unlock(&c0->lock);
3120                 ast_mutex_unlock(&c1->lock);
3121                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3122                 return AST_BRIDGE_RETRY;
3123         }
3124
3125         if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3126                 if (p0->owner && p1->owner) {
3127                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
3128                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
3129                                 master = p0;
3130                                 slave = p1;
3131                                 inconf = 1;
3132                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
3133                                 master = p1;
3134                                 slave = p0;
3135                                 inconf = 1;
3136                         } else {
3137                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
3138                                 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
3139                                         p0->channel,
3140                                         oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3141                                         p0->subs[SUB_REAL].inthreeway, p0->channel,
3142                                         oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3143                                         p1->subs[SUB_REAL].inthreeway);
3144                         }
3145                         nothingok = 0;
3146                 }
3147         } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
3148                 if (p1->subs[SUB_THREEWAY].inthreeway) {
3149                         master = p1;
3150                         slave = p0;
3151                         nothingok = 0;
3152                 }
3153         } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
3154                 if (p0->subs[SUB_THREEWAY].inthreeway) {
3155                         master = p0;
3156                         slave = p1;
3157                         nothingok = 0;
3158                 }
3159         } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
3160                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
3161                    don't put us in anything */
3162                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
3163                         master = p1;
3164                         slave = p0;
3165                         nothingok = 0;
3166                 }
3167         } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
3168                 /* Same as previous */
3169                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
3170                         master = p0;
3171                         slave = p1;
3172                         nothingok = 0;
3173                 }
3174         }
3175         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
3176                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
3177         if (master && slave) {
3178                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
3179                    in an active threeway call with a channel that is ringing, we should
3180                    indicate ringing. */
3181                 if ((oi1 == SUB_THREEWAY) && 
3182                     p1->subs[SUB_THREEWAY].inthreeway && 
3183                     p1->subs[SUB_REAL].owner && 
3184                     p1->subs[SUB_REAL].inthreeway && 
3185                     (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3186                         ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
3187                         tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
3188                         os1 = p1->subs[SUB_REAL].owner->_state;
3189                 } else {
3190                         ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
3191                         tone_zone_play_tone(p0->subs[oi0].zfd, -1);
3192                 }
3193                 if ((oi0 == SUB_THREEWAY) && 
3194                     p0->subs[SUB_THREEWAY].inthreeway && 
3195                     p0->subs[SUB_REAL].owner && 
3196                     p0->subs[SUB_REAL].inthreeway && 
3197                     (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
3198                         ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
3199                         tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
3200                         os0 = p0->subs[SUB_REAL].owner->_state;
3201                 } else {
3202                         ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
3203                         tone_zone_play_tone(p1->subs[oi0].zfd, -1);
3204                 }
3205                 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3206                         if (!p0->echocanbridged || !p1->echocanbridged) {
3207                                 /* Disable echo cancellation if appropriate */
3208                                 zt_disable_ec(p0);
3209                                 zt_disable_ec(p1);
3210                         }
3211                 }
3212                 zt_link(slave, master);
3213                 master->inconference = inconf;
3214         } else if (!nothingok)
3215                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
3216
3217         update_conf(p0);
3218         update_conf(p1);
3219         t0 = p0->subs[SUB_REAL].inthreeway;
3220         t1 = p1->subs[SUB_REAL].inthreeway;
3221
3222         ast_mutex_unlock(&p0->lock);
3223         ast_mutex_unlock(&p1->lock);
3224
3225         ast_mutex_unlock(&c0->lock);
3226         ast_mutex_unlock(&c1->lock);
3227
3228         /* Native bridge failed */
3229         if ((!master || !slave) && !nothingok) {
3230                 zt_enable_ec(p0);
3231                 zt_enable_ec(p1);
3232                 return AST_BRIDGE_FAILED;
3233         }
3234         
3235         if (option_verbose > 2) 
3236                 ast_verbose(VERBOSE_PREFIX_3 "Native bridging %s and %s\n", c0->name, c1->name);
3237
3238         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3239                 disable_dtmf_detect(op0);
3240
3241         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3242                 disable_dtmf_detect(op1);
3243
3244         for (;;) {
3245                 struct ast_channel *c0_priority[2] = {c0, c1};
3246                 struct ast_channel *c1_priority[2] = {c1, c0};
3247
3248                 /* Here's our main loop...  Start by locking things, looking for private parts, 
3249                    and then balking if anything is wrong */
3250                 ast_mutex_lock(&c0->lock);
3251                 ast_mutex_lock(&c1->lock);
3252                 p0 = c0->tech_pvt;
3253                 p1 = c1->tech_pvt;
3254
3255                 if (op0 == p0)
3256                         i0 = zt_get_index(c0, p0, 1);
3257                 if (op1 == p1)
3258                         i1 = zt_get_index(c1, p1, 1);
3259                 ast_mutex_unlock(&c0->lock);
3260                 ast_mutex_unlock(&c1->lock);
3261
3262                 if (!timeoutms || 
3263                     (op0 != p0) ||
3264                     (op1 != p1) || 
3265                     (ofd0 != c0->fds[0]) || 
3266                     (ofd1 != c1->fds[0]) ||
3267                     (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) || 
3268                     (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) || 
3269                     (oc0 != p0->owner) || 
3270                     (oc1 != p1->owner) ||
3271                     (t0 != p0->subs[SUB_REAL].inthreeway) ||
3272                     (t1 != p1->subs[SUB_REAL].inthreeway) ||
3273                     (oi0 != i0) ||
3274                     (oi1 != i1)) {
3275                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
3276                                 op0->channel, oi0, op1->channel, oi1);
3277                         res = AST_BRIDGE_RETRY;
3278                         goto return_from_bridge;
3279                 }
3280
3281 #ifdef PRI_2BCT
3282                 q931c0 = p0->call;
3283                 q931c1 = p1->call;
3284                 if (p0->transfer && p1->transfer 
3285                     && q931c0 && q931c1 
3286                     && !triedtopribridge) {
3287                         pri_channel_bridge(q931c0, q931c1);
3288                         triedtopribridge = 1;
3289                 }
3290 #endif
3291
3292                 who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &timeoutms);
3293                 if (!who) {
3294                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
3295                         continue;
3296                 }
3297                 f = ast_read(who);
3298                 if (!f || (f->frametype == AST_FRAME_CONTROL)) {
3299                         *fo = f;
3300                         *rc = who;
3301                         res = AST_BRIDGE_COMPLETE;
3302                         goto return_from_bridge;
3303                 }
3304                 if (f->frametype == AST_FRAME_DTMF) {
3305                         if ((who == c0) && p0->pulsedial) {
3306                                 ast_write(c1, f);
3307                         } else if ((who == c1) && p1->pulsedial) {
3308                                 ast_write(c0, f);
3309                         } else {
3310                                 *fo = f;
3311                                 *rc = who;
3312                                 res = AST_BRIDGE_COMPLETE;
3313                                 goto return_from_bridge;
3314                         }
3315                 }
3316                 ast_frfree(f);
3317                 
3318                 /* Swap who gets priority */
3319                 priority = !priority;
3320         }
3321
3322 return_from_bridge:
3323         if (op0 == p0)
3324                 zt_enable_ec(p0);
3325
3326         if (op1 == p1)
3327                 zt_enable_ec(p1);
3328
3329         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0) && (oi0 == SUB_REAL))
3330                 enable_dtmf_detect(op0);
3331
3332         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1) && (oi1 == SUB_REAL))
3333                 enable_dtmf_detect(op1);
3334
3335         zt_unlink(slave, master, 1);
3336
3337         return res;
3338 }
3339
3340 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3341 {
3342         struct zt_pvt *p = newchan->tech_pvt;
3343         int x;
3344         ast_mutex_lock(&p->lock);
3345         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3346         if (p->owner == oldchan) {
3347                 p->owner = newchan;
3348         }
3349         for (x = 0; x < 3; x++)
3350                 if (p->subs[x].owner == oldchan) {
3351                         if (!x)
3352                                 zt_unlink(NULL, p, 0);
3353                         p->subs[x].owner = newchan;
3354                 }
3355         if (newchan->_state == AST_STATE_RINGING) 
3356                 zt_indicate(newchan, AST_CONTROL_RINGING, NULL, 0);
3357         update_conf(p);
3358         ast_mutex_unlock(&p->lock);
3359         return 0;
3360 }
3361
3362 static int zt_ring_phone(struct zt_pvt *p)
3363 {
3364         int x;
3365         int res;
3366         /* Make sure our transmit state is on hook */
3367         x = 0;
3368         x = ZT_ONHOOK;
3369         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3370         do {
3371                 x = ZT_RING;
3372                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3373 #if 0
3374                 printf("Res: %d, error: %s\n", res, strerror(errno));
3375 #endif                                          
3376                 if (res) {
3377                         switch (errno) {
3378                         case EBUSY:
3379                         case EINTR:
3380                                 /* Wait just in case */
3381                                 usleep(10000);
3382                                 continue;
3383                         case EINPROGRESS:
3384                                 res = 0;
3385                                 break;
3386                         default:
3387                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3388                                 res = 0;
3389                         }
3390                 }
3391         } while (res);
3392         return res;
3393 }
3394
3395 static void *ss_thread(void *data);
3396
3397 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3398
3399 static int attempt_transfer(struct zt_pvt *p)
3400 {
3401         /* In order to transfer, we need at least one of the channels to
3402            actually be in a call bridge.  We can't conference two applications
3403            together (but then, why would we want to?) */
3404         if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3405                 /* The three-way person we're about to transfer to could still be in MOH, so
3406                    stop if now if appropriate */
3407                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3408                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3409                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3410                         ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3411                 }
3412                 if (p->subs[SUB_REAL].owner->cdr) {
3413                         /* Move CDR from second channel to current one */
3414                         p->subs[SUB_THREEWAY].owner->cdr =
3415                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3416                         p->subs[SUB_REAL].owner->cdr = NULL;
3417                 }
3418                 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3419                         /* Move CDR from second channel's bridge to current one */
3420                         p->subs[SUB_THREEWAY].owner->cdr =
3421                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3422                         ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3423                 }
3424                  if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3425                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3426                                         ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3427                         return -1;
3428                 }
3429                 /* Orphan the channel after releasing the lock */
3430                 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3431                 unalloc_sub(p, SUB_THREEWAY);
3432         } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3433                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
3434                         ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3435                 }
3436                 ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3437                 if (p->subs[SUB_THREEWAY].owner->cdr) {
3438                         /* Move CDR from second channel to current one */
3439                         p->subs[SUB_REAL].owner->cdr = 
3440                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3441                         p->subs[SUB_THREEWAY].owner->cdr = NULL;
3442                 }
3443                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3444                         /* Move CDR from second channel's bridge to current