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