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