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