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