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