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