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