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