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