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