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