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