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