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