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