missed a line...
[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
1905                 c += p->stripmsd;
1906
1907                 switch (p->sig) {
1908                 case SIG_FEATD:
1909                         l = ast->cid.cid_num;
1910                         if (l) 
1911                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1912                         else
1913                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1914                         break;
1915                 case SIG_FEATDMF:
1916                         l = ast->cid.cid_num;
1917                         if (l) 
1918                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1919                         else
1920                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1921                         break;
1922                 case SIG_FEATDMF_TA:
1923                 {
1924                         char *cic = NULL, *ozz = NULL;
1925
1926                         /* If you have to go through a Tandem Access point you need to use this */
1927                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1928                         if (!ozz)
1929                                 ozz = defaultozz;
1930                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1931                         if (!cic)
1932                                 cic = defaultcic;
1933                         if (!ozz || !cic) {
1934                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1935                                 ast_mutex_unlock(&p->lock);
1936                                 return -1;
1937                         }
1938                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1939                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1940                         p->whichwink = 0;
1941                 }
1942                         break;
1943                 case SIG_E911:
1944                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1945                         break;
1946                 case SIG_FEATB:
1947                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
1948                         break;
1949                 default:
1950                         if (p->pulse)
1951                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
1952                         else
1953                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
1954                         break;
1955                 }
1956
1957                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1958                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1959                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1960                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1961                         p->echobreak = 1;
1962                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1963                 } else
1964                         p->echobreak = 0;
1965                 if (!res) {
1966                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1967                                 x = ZT_ONHOOK;
1968                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1969                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1970                                 ast_mutex_unlock(&p->lock);
1971                                 return -1;
1972                         }
1973                 } else
1974                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1975                 p->dialing = 1;
1976                 if (ast_strlen_zero(c))
1977                         p->dialednone = 1;
1978                 ast_setstate(ast, AST_STATE_DIALING);
1979                 break;
1980         case 0:
1981                 /* Special pseudo -- automatically up*/
1982                 ast_setstate(ast, AST_STATE_UP);
1983                 break;          
1984         case SIG_PRI:
1985                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1986                 p->dialdest[0] = '\0';
1987                 break;
1988         default:
1989                 ast_log(LOG_DEBUG, "not yet implemented\n");
1990                 ast_mutex_unlock(&p->lock);
1991                 return -1;
1992         }
1993 #ifdef ZAPATA_PRI
1994         if (p->pri) {
1995                 struct pri_sr *sr;
1996                 int pridialplan;
1997                 int dp_strip;
1998                 int prilocaldialplan;
1999                 int ldp_strip;
2000                 int exclusive;
2001
2002                 c = strchr(dest, '/');
2003                 if (c)
2004                         c++;
2005                 else
2006                         c = dest;
2007                 if (!p->hidecallerid) {
2008                         l = ast->cid.cid_num;
2009                         n = ast->cid.cid_name;
2010                 } else {
2011                         l = NULL;
2012                         n = NULL;
2013                 }
2014                 if (strlen(c) < p->stripmsd) {
2015                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2016                         ast_mutex_unlock(&p->lock);
2017                         return -1;
2018                 }
2019                 if (p->sig != SIG_FXSKS) {
2020                         p->dop.op = ZT_DIAL_OP_REPLACE;
2021                         s = strchr(c + p->stripmsd, 'w');
2022                         if (s) {
2023                                 if (strlen(s) > 1)
2024                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2025                                 else
2026                                         p->dop.dialstr[0] = '\0';
2027                                 *s = '\0';
2028                         } else {
2029                                 p->dop.dialstr[0] = '\0';
2030                         }
2031                 }
2032                 if (pri_grab(p, p->pri)) {
2033                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2034                         ast_mutex_unlock(&p->lock);
2035                         return -1;
2036                 }
2037                 if (!(p->call = pri_new_call(p->pri->pri))) {
2038                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2039                         pri_rel(p->pri);
2040                         ast_mutex_unlock(&p->lock);
2041                         return -1;
2042                 }
2043                 if (!(sr = pri_sr_new())) {
2044                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2045                         pri_rel(p->pri);
2046                         ast_mutex_unlock(&p->lock);
2047                 }
2048                 if (p->bearer || (p->sig == SIG_FXSKS)) {
2049                         if (p->bearer) {
2050                                 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);
2051                                 p->bearer->call = p->call;
2052                         } else
2053                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2054                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2055                 }
2056                 p->digital = IS_DIGITAL(ast->transfercapability);
2057                 /* Add support for exclusive override */
2058                 if (p->priexclusive)
2059                         exclusive = 1;
2060                 else {
2061                 /* otherwise, traditional behavior */
2062                         if (p->pri->nodetype == PRI_NETWORK)
2063                                 exclusive = 0;
2064                         else
2065                                 exclusive = 1;
2066                 }
2067                 
2068                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2069                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2070                                         (p->digital ? -1 : 
2071                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2072                 if (p->pri->facilityenable)
2073                         pri_facility_enable(p->pri->pri);
2074
2075                 if (option_verbose > 2)
2076                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2077                 dp_strip = 0;
2078                 pridialplan = p->pri->dialplan - 1;
2079                 if (pridialplan == -2) { /* compute dynamically */
2080                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2081                                 dp_strip = strlen(p->pri->internationalprefix);
2082                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2083                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2084                                 dp_strip = strlen(p->pri->nationalprefix);
2085                                 pridialplan = PRI_NATIONAL_ISDN;
2086                         } else {
2087                                 pridialplan = PRI_LOCAL_ISDN;
2088                         }
2089                 }
2090                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  s ? 1 : 0);
2091
2092                 ldp_strip = 0;
2093                 prilocaldialplan = p->pri->localdialplan - 1;
2094                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2095                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2096                                 ldp_strip = strlen(p->pri->internationalprefix);
2097                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2098                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2099                                 ldp_strip = strlen(p->pri->nationalprefix);
2100                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2101                         } else {
2102                                 prilocaldialplan = PRI_LOCAL_ISDN;
2103                         }
2104                 }
2105                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan, 
2106                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
2107                                                  PRES_NUMBER_NOT_AVAILABLE);
2108                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
2109                 if (pri_setup(p->pri->pri, p->call,  sr)) {
2110                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2111                                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2112                         pri_rel(p->pri);
2113                         ast_mutex_unlock(&p->lock);
2114                         pri_sr_free(sr);
2115                         return -1;
2116                 }
2117                 pri_sr_free(sr);
2118                 ast_setstate(ast, AST_STATE_DIALING);
2119                 pri_rel(p->pri);
2120         }
2121 #endif          
2122         ast_mutex_unlock(&p->lock);
2123         return 0;
2124 }
2125
2126 static void destroy_zt_pvt(struct zt_pvt **pvt)
2127 {
2128         struct zt_pvt *p = *pvt;
2129         /* Remove channel from the list */
2130         if(p->prev)
2131                 p->prev->next = p->next;
2132         if(p->next)
2133                 p->next->prev = p->prev;
2134         ast_mutex_destroy(&p->lock);
2135         free(p);
2136         *pvt = NULL;
2137 }
2138
2139 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2140 {
2141         int owned = 0;
2142         int i = 0;
2143
2144         if (!now) {
2145                 if (cur->owner) {
2146                         owned = 1;
2147                 }
2148
2149                 for (i = 0; i < 3; i++) {
2150                         if (cur->subs[i].owner) {
2151                                 owned = 1;
2152                         }
2153                 }
2154                 if (!owned) {
2155                         if (prev) {
2156                                 prev->next = cur->next;
2157                                 if (prev->next)
2158                                         prev->next->prev = prev;
2159                                 else
2160                                         ifend = prev;
2161                         } else {
2162                                 iflist = cur->next;
2163                                 if (iflist)
2164                                         iflist->prev = NULL;
2165                                 else
2166                                         ifend = NULL;
2167                         }
2168                         if (cur->subs[SUB_REAL].zfd > -1) {
2169                                 zt_close(cur->subs[SUB_REAL].zfd);
2170                         }
2171                         destroy_zt_pvt(&cur);
2172                 }
2173         } else {
2174                 if (prev) {
2175                         prev->next = cur->next;
2176                         if (prev->next)
2177                                 prev->next->prev = prev;
2178                         else
2179                                 ifend = prev;
2180                 } else {
2181                         iflist = cur->next;
2182                         if (iflist)
2183                                 iflist->prev = NULL;
2184                         else
2185                                 ifend = NULL;
2186                 }
2187                 if (cur->subs[SUB_REAL].zfd > -1) {
2188                         zt_close(cur->subs[SUB_REAL].zfd);
2189                 }
2190                 destroy_zt_pvt(&cur);
2191         }
2192         return 0;
2193 }
2194
2195 #ifdef ZAPATA_PRI
2196 int pri_is_up(struct zt_pri *pri)
2197 {
2198         int x;
2199         for (x=0;x<NUM_DCHANS;x++) {
2200                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2201                         return 1;
2202         }
2203         return 0;
2204 }
2205
2206 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2207 {
2208         bearer->owner = &inuse;
2209         bearer->realcall = crv;
2210         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2211         if (crv->subs[SUB_REAL].owner)
2212                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2213         crv->bearer = bearer;
2214         crv->call = bearer->call;
2215         crv->pri = pri;
2216         return 0;
2217 }
2218
2219 static char *pri_order(int level)
2220 {
2221         switch(level) {
2222         case 0:
2223                 return "Primary";
2224         case 1:
2225                 return "Secondary";
2226         case 2:
2227                 return "Tertiary";
2228         case 3:
2229                 return "Quaternary";
2230         default:
2231                 return "<Unknown>";
2232         }               
2233 }
2234
2235 /* Returns fd of the active dchan */
2236 int pri_active_dchan_fd(struct zt_pri *pri)
2237 {
2238         int x = -1;
2239
2240         for (x = 0; x < NUM_DCHANS; x++) {
2241                 if ((pri->dchans[x] == pri->pri))
2242                         break;
2243         }
2244
2245         return pri->fds[x];
2246 }
2247
2248 int pri_find_dchan(struct zt_pri *pri)
2249 {
2250         int oldslot = -1;
2251         struct pri *old;
2252         int newslot = -1;
2253         int x;
2254         old = pri->pri;
2255         for(x=0;x<NUM_DCHANS;x++) {
2256                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2257                         newslot = x;
2258                 if (pri->dchans[x] == old) {
2259                         oldslot = x;
2260                 }
2261         }
2262         if (newslot < 0) {
2263                 newslot = 0;
2264                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2265                         pri->dchannels[newslot]);
2266         }
2267         if (old && (oldslot != newslot))
2268                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2269                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2270         pri->pri = pri->dchans[newslot];
2271         return 0;
2272 }
2273 #endif
2274
2275 static int zt_hangup(struct ast_channel *ast)
2276 {
2277         int res;
2278         int index,x, law;
2279         /*static int restore_gains(struct zt_pvt *p);*/
2280         struct zt_pvt *p = ast->tech_pvt;
2281         struct zt_pvt *tmp = NULL;
2282         struct zt_pvt *prev = NULL;
2283         ZT_PARAMS par;
2284
2285         if (option_debug)
2286                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2287         if (!ast->tech_pvt) {
2288                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2289                 return 0;
2290         }
2291         
2292         ast_mutex_lock(&p->lock);
2293         
2294         index = zt_get_index(ast, p, 1);
2295
2296         if (p->sig == SIG_PRI) {
2297                 x = 1;
2298                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2299         }
2300
2301         x = 0;
2302         zt_confmute(p, 0);
2303         restore_gains(p);
2304         if (p->origcid_num) {
2305                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2306                 free(p->origcid_num);
2307                 p->origcid_num = NULL;
2308         }       
2309         if (p->origcid_name) {
2310                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2311                 free(p->origcid_name);
2312                 p->origcid_name = NULL;
2313         }       
2314         if (p->dsp)
2315                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2316         if (p->exten)
2317                 p->exten[0] = '\0';
2318
2319         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2320                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2321         p->ignoredtmf = 0;
2322         
2323         if (index > -1) {
2324                 /* Real channel, do some fixup */
2325                 p->subs[index].owner = NULL;
2326                 p->subs[index].needanswer = 0;
2327                 p->subs[index].needflash = 0;
2328                 p->subs[index].needringing = 0;
2329                 p->subs[index].needbusy = 0;
2330                 p->subs[index].needcongestion = 0;
2331                 p->subs[index].linear = 0;
2332                 p->subs[index].needcallerid = 0;
2333                 p->polarity = POLARITY_IDLE;
2334                 zt_setlinear(p->subs[index].zfd, 0);
2335                 if (index == SUB_REAL) {
2336                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2337                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2338                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2339                                         /* We had flipped over to answer a callwait and now it's gone */
2340                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2341                                         /* Move to the call-wait, but un-own us until they flip back. */
2342                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2343                                         unalloc_sub(p, SUB_CALLWAIT);
2344                                         p->owner = NULL;
2345                                 } else {
2346                                         /* The three way hung up, but we still have a call wait */
2347                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2348                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2349                                         unalloc_sub(p, SUB_THREEWAY);
2350                                         if (p->subs[SUB_REAL].inthreeway) {
2351                                                 /* This was part of a three way call.  Immediately make way for
2352                                                    another call */
2353                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2354                                                 p->owner = p->subs[SUB_REAL].owner;
2355                                         } else {
2356                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2357                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2358                                                 p->owner = NULL;
2359                                         }
2360                                         p->subs[SUB_REAL].inthreeway = 0;
2361                                 }
2362                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2363                                 /* Move to the call-wait and switch back to them. */
2364                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2365                                 unalloc_sub(p, SUB_CALLWAIT);
2366                                 p->owner = p->subs[SUB_REAL].owner;
2367                                 if (p->owner->_state != AST_STATE_UP)
2368                                         p->subs[SUB_REAL].needanswer = 1;
2369                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2370                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2371                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2372                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2373                                 unalloc_sub(p, SUB_THREEWAY);
2374                                 if (p->subs[SUB_REAL].inthreeway) {
2375                                         /* This was part of a three way call.  Immediately make way for
2376                                            another call */
2377                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2378                                         p->owner = p->subs[SUB_REAL].owner;
2379                                 } else {
2380                                         /* This call hasn't been completed yet...  Set owner to NULL */
2381                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2382                                         p->owner = NULL;
2383                                 }
2384                                 p->subs[SUB_REAL].inthreeway = 0;
2385                         }
2386                 } else if (index == SUB_CALLWAIT) {
2387                         /* Ditch the holding callwait call, and immediately make it availabe */
2388                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2389                                 /* This is actually part of a three way, placed on hold.  Place the third part
2390                                    on music on hold now */
2391                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2392                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2393                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2394                                 /* Make it the call wait now */
2395                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2396                                 unalloc_sub(p, SUB_THREEWAY);
2397                         } else
2398                                 unalloc_sub(p, SUB_CALLWAIT);
2399                 } else if (index == SUB_THREEWAY) {
2400                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2401                                 /* The other party of the three way call is currently in a call-wait state.
2402                                    Start music on hold for them, and take the main guy out of the third call */
2403                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2404                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2405                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2406                         }
2407                         p->subs[SUB_REAL].inthreeway = 0;
2408                         /* If this was part of a three way call index, let us make
2409                            another three way call */
2410                         unalloc_sub(p, SUB_THREEWAY);
2411                 } else {
2412                         /* This wasn't any sort of call, but how are we an index? */
2413                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2414                 }
2415         }
2416
2417
2418         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2419                 p->owner = NULL;
2420                 p->ringt = 0;
2421                 p->distinctivering = 0;
2422                 p->confirmanswer = 0;
2423                 p->cidrings = 1;
2424                 p->outgoing = 0;
2425                 p->digital = 0;
2426                 p->faxhandled = 0;
2427                 p->pulsedial = 0;
2428                 p->onhooktime = time(NULL);
2429 #ifdef ZAPATA_PRI
2430                 p->proceeding = 0;
2431                 p->alerting = 0;
2432                 p->setup_ack = 0;
2433 #endif          
2434                 if (p->dsp) {
2435                         ast_dsp_free(p->dsp);
2436                         p->dsp = NULL;
2437                 }
2438
2439                 law = ZT_LAW_DEFAULT;
2440                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2441                 if (res < 0) 
2442                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2443                 /* Perform low level hangup if no owner left */
2444 #ifdef ZAPATA_PRI
2445                 if (p->pri) {
2446                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2447                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2448                                 if (!pri_grab(p, p->pri)) {
2449                                         if (p->alreadyhungup) {
2450                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2451                                                 pri_hangup(p->pri->pri, p->call, -1);
2452                                                 p->call = NULL;
2453                                                 if (p->bearer) 
2454                                                         p->bearer->call = NULL;
2455                                         } else {
2456                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2457                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2458                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2459                                                 p->alreadyhungup = 1;
2460                                                 if (p->bearer)
2461                                                         p->bearer->alreadyhungup = 1;
2462                                                 if (cause) {
2463                                                         if (atoi(cause))
2464                                                                 icause = atoi(cause);
2465                                                 }
2466                                                 pri_hangup(p->pri->pri, p->call, icause);
2467                                         }
2468                                         if (res < 0) 
2469                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2470                                         pri_rel(p->pri);                        
2471                                 } else {
2472                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2473                                         res = -1;
2474                                 }
2475                         } else {
2476                                 if (p->bearer)
2477                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2478                                 p->call = NULL;
2479                                 res = 0;
2480                         }
2481                 }
2482 #endif
2483 #ifdef ZAPATA_R2
2484                 if (p->sig == SIG_R2) {
2485                         if (p->hasr2call) {
2486                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2487                                 p->hasr2call = 0;
2488                                 res = 0;
2489                         } else
2490                                 res = 0;
2491
2492                 }
2493 #endif
2494                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2495                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2496                 if (res < 0) {
2497                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2498                 }
2499                 switch(p->sig) {
2500                 case SIG_FXOGS:
2501                 case SIG_FXOLS:
2502                 case SIG_FXOKS:
2503                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2504                         if (!res) {
2505 #if 0
2506                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2507 #endif
2508                                 /* If they're off hook, try playing congestion */
2509                                 if ((par.rxisoffhook) && (!p->radio))
2510                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2511                                 else
2512                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2513                         }
2514                         break;
2515                 case SIG_FXSGS:
2516                 case SIG_FXSLS:
2517                 case SIG_FXSKS:
2518                         /* Make sure we're not made available for at least two seconds assuming
2519                            we were actually used for an inbound or outbound call. */
2520                         if (ast->_state != AST_STATE_RESERVED) {
2521                                 time(&p->guardtime);
2522                                 p->guardtime += 2;
2523                         }
2524                         break;
2525                 default:
2526                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2527                 }
2528                 if (p->cidspill)
2529                         free(p->cidspill);
2530                 if (p->sig)
2531                         zt_disable_ec(p);
2532                 x = 0;
2533                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2534                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2535                 p->didtdd = 0;
2536                 p->cidspill = NULL;
2537                 p->callwaitcas = 0;
2538                 p->callwaiting = p->permcallwaiting;
2539                 p->hidecallerid = p->permhidecallerid;
2540                 p->dialing = 0;
2541                 p->rdnis[0] = '\0';
2542                 update_conf(p);
2543                 reset_conf(p);
2544                 /* Restore data mode */
2545                 if (p->sig == SIG_PRI) {
2546                         x = 0;
2547                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2548                 }
2549 #ifdef ZAPATA_PRI
2550                 if (p->bearer) {
2551                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2552                         /* Free up the bearer channel as well, and
2553                            don't use its file descriptor anymore */
2554                         update_conf(p->bearer);
2555                         reset_conf(p->bearer);
2556                         p->bearer->owner = NULL;
2557                         p->bearer->realcall = NULL;
2558                         p->bearer = NULL;
2559                         p->subs[SUB_REAL].zfd = -1;
2560                         p->pri = NULL;
2561                 }
2562 #endif
2563                 restart_monitor();
2564         }
2565
2566
2567         p->callwaitingrepeat = 0;
2568         p->cidcwexpire = 0;
2569         ast->tech_pvt = NULL;
2570         ast_mutex_unlock(&p->lock);
2571         ast_mutex_lock(&usecnt_lock);
2572         usecnt--;
2573         if (usecnt < 0) 
2574                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2575         ast_mutex_unlock(&usecnt_lock);
2576         ast_update_use_count();
2577         if (option_verbose > 2) 
2578                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2579
2580         ast_mutex_lock(&iflock);
2581         tmp = iflist;
2582         prev = NULL;
2583         if (p->destroy) {
2584                 while (tmp) {
2585                         if (tmp == p) {
2586                                 destroy_channel(prev, tmp, 0);
2587                                 break;
2588                         } else {
2589                                 prev = tmp;
2590                                 tmp = tmp->next;
2591                         }
2592                 }
2593         }
2594         ast_mutex_unlock(&iflock);
2595         return 0;
2596 }
2597
2598 static int zt_answer(struct ast_channel *ast)
2599 {
2600         struct zt_pvt *p = ast->tech_pvt;
2601         int res=0;
2602         int index;
2603         int oldstate = ast->_state;
2604         ast_setstate(ast, AST_STATE_UP);
2605         ast_mutex_lock(&p->lock);
2606         index = zt_get_index(ast, p, 0);
2607         if (index < 0)
2608                 index = SUB_REAL;
2609         /* nothing to do if a radio channel */
2610         if (p->radio) {
2611                 ast_mutex_unlock(&p->lock);
2612                 return 0;
2613         }
2614         switch(p->sig) {
2615         case SIG_FXSLS:
2616         case SIG_FXSGS:
2617         case SIG_FXSKS:
2618                 p->ringt = 0;
2619                 /* Fall through */
2620         case SIG_EM:
2621         case SIG_EM_E1:
2622         case SIG_EMWINK:
2623         case SIG_FEATD:
2624         case SIG_FEATDMF:
2625         case SIG_E911:
2626         case SIG_FEATB:
2627         case SIG_SF:
2628         case SIG_SFWINK:
2629         case SIG_SF_FEATD:
2630         case SIG_SF_FEATDMF:
2631         case SIG_SF_FEATB:
2632         case SIG_FXOLS:
2633         case SIG_FXOGS:
2634         case SIG_FXOKS:
2635                 /* Pick up the line */
2636                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2637                 if(p->hanguponpolarityswitch) {
2638                         gettimeofday(&p->polaritydelaytv, NULL);
2639                 }
2640                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2641                 tone_zone_play_tone(p->subs[index].zfd, -1);
2642                 p->dialing = 0;
2643                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2644                         if (oldstate == AST_STATE_RINGING) {
2645                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2646                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2647                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2648                                 p->owner = p->subs[SUB_REAL].owner;
2649                         }
2650                 }
2651                 if (p->sig & __ZT_SIG_FXS) {
2652                         zt_enable_ec(p);
2653                         zt_train_ec(p);
2654                 }
2655                 break;
2656 #ifdef ZAPATA_PRI
2657         case SIG_PRI:
2658                 /* Send a pri acknowledge */
2659                 if (!pri_grab(p, p->pri)) {
2660                         p->proceeding = 2;
2661                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2662                         pri_rel(p->pri);
2663                 } else {
2664                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2665                         res= -1;
2666                 }
2667                 break;
2668 #endif
2669 #ifdef ZAPATA_R2
2670         case SIG_R2:
2671                 res = mfcr2_AnswerCall(p->r2, NULL);
2672                 if (res)
2673                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2674                 break;
2675 #endif                  
2676         case 0:
2677                 ast_mutex_unlock(&p->lock);
2678                 return 0;
2679         default:
2680                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2681                 res = -1;
2682         }
2683         ast_mutex_unlock(&p->lock);
2684         return res;
2685 }
2686
2687 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2688 {
2689         char *cp;
2690         signed char *scp;
2691         int x;
2692         int index;
2693         struct zt_pvt *p = chan->tech_pvt;
2694
2695         /* all supported options require data */
2696         if (!data || (datalen < 1)) {
2697                 errno = EINVAL;
2698                 return -1;
2699         }
2700
2701         switch(option) {
2702         case AST_OPTION_TXGAIN:
2703                 scp = (signed char *) data;
2704                 index = zt_get_index(chan, p, 0);
2705                 if (index < 0) {
2706                         ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2707                         return -1;
2708                 }
2709                 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2710                 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2711         case AST_OPTION_RXGAIN:
2712                 scp = (signed char *) data;
2713                 index = zt_get_index(chan, p, 0);
2714                 if (index < 0) {
2715                         ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2716                         return -1;
2717                 }
2718                 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2719                 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2720         case AST_OPTION_TONE_VERIFY:
2721                 if (!p->dsp)
2722                         break;
2723                 cp = (char *) data;
2724                 switch (*cp) {
2725                 case 1:
2726                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2727                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2728                         break;
2729                 case 2:
2730                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2731                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2732                         break;
2733                 default:
2734                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2735                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2736                         break;
2737                 }
2738                 break;
2739         case AST_OPTION_TDD:
2740                 /* turn on or off TDD */
2741                 cp = (char *) data;
2742                 p->mate = 0;
2743                 if (!*cp) { /* turn it off */
2744                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2745                         if (p->tdd) tdd_free(p->tdd);
2746                         p->tdd = 0;
2747                         break;
2748                 }
2749                 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2750                         (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2751                 zt_disable_ec(p);
2752                 /* otherwise, turn it on */
2753                 if (!p->didtdd) { /* if havent done it yet */
2754                         unsigned char mybuf[41000],*buf;
2755                         int size,res,fd,len;
2756                         struct pollfd fds[1];
2757
2758                         buf = mybuf;
2759                         memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2760                         ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
2761                         len = 40000;
2762                         index = zt_get_index(chan, p, 0);
2763                         if (index < 0) {
2764                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2765                                 return -1;
2766                         }
2767                         fd = p->subs[index].zfd;
2768                         while(len) {
2769                                 if (ast_check_hangup(chan)) return -1;
2770                                 size = len;
2771                                 if (size > READ_SIZE)
2772                                         size = READ_SIZE;
2773                                 fds[0].fd = fd;
2774                                 fds[0].events = POLLPRI | POLLOUT;
2775                                 fds[0].revents = 0;
2776                                 res = poll(fds, 1, -1);
2777                                 if (!res) {
2778                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2779                                         continue;
2780                                 }
2781                                 /* if got exception */
2782                                 if (fds[0].revents & POLLPRI) return -1;
2783                                 if (!(fds[0].revents & POLLOUT)) {
2784                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2785                                         continue;
2786                                 }
2787                                 res = write(fd, buf, size);
2788                                 if (res != size) {
2789                                         if (res == -1) return -1;
2790                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2791                                         break;
2792                                 }
2793                                 len -= size;
2794                                 buf += size;
2795                         }
2796                         p->didtdd = 1; /* set to have done it now */            
2797                 }
2798                 if (*cp == 2) { /* Mate mode */
2799                         if (p->tdd) tdd_free(p->tdd);
2800                         p->tdd = 0;
2801                         p->mate = 1;
2802                         break;
2803                 }               
2804                 if (!p->tdd) { /* if we dont have one yet */
2805                         p->tdd = tdd_new(); /* allocate one */
2806                 }               
2807                 break;
2808         case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2809                 if (!p->dsp)
2810                         break;
2811                 cp = (char *) data;
2812                 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2813                         *cp ? "ON" : "OFF", (int) *cp, chan->name);
2814                 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
2815                 break;
2816         case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2817                 cp = (char *) data;
2818                 if (!*cp) {             
2819                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2820                         x = 0;
2821                         zt_disable_ec(p);
2822                 } else {                
2823                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2824                         x = 1;
2825                 }
2826                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2827                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2828                 break;
2829         }
2830         errno = 0;
2831
2832         return 0;
2833 }
2834
2835 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2836 {
2837         /* Unlink a specific slave or all slaves/masters from a given master */
2838         int x;
2839         int hasslaves;
2840         if (!master)
2841                 return;
2842         if (needlock) {
2843                 ast_mutex_lock(&master->lock);
2844                 if (slave) {
2845                         while(ast_mutex_trylock(&slave->lock)) {
2846                                 ast_mutex_unlock(&master->lock);
2847                                 usleep(1);
2848                                 ast_mutex_lock(&master->lock);
2849                         }
2850                 }
2851         }
2852         hasslaves = 0;
2853         for (x=0;x<MAX_SLAVES;x++) {
2854                 if (master->slaves[x]) {
2855                         if (!slave || (master->slaves[x] == slave)) {
2856                                 /* Take slave out of the conference */
2857                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2858                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2859                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2860                                 master->slaves[x]->master = NULL;
2861                                 master->slaves[x] = NULL;
2862                         } else
2863                                 hasslaves = 1;
2864                 }
2865                 if (!hasslaves)
2866                         master->inconference = 0;
2867         }
2868         if (!slave) {
2869                 if (master->master) {
2870                         /* Take master out of the conference */
2871                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2872                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2873                         hasslaves = 0;
2874                         for (x=0;x<MAX_SLAVES;x++) {
2875                                 if (master->master->slaves[x] == master)
2876                                         master->master->slaves[x] = NULL;
2877                                 else if (master->master->slaves[x])
2878                                         hasslaves = 1;
2879                         }
2880                         if (!hasslaves)
2881                                 master->master->inconference = 0;
2882                 }
2883                 master->master = NULL;
2884         }
2885         update_conf(master);
2886         if (needlock) {
2887                 if (slave)
2888                         ast_mutex_unlock(&slave->lock);
2889                 ast_mutex_unlock(&master->lock);
2890         }
2891 }
2892
2893 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2894         int x;
2895         if (!slave || !master) {
2896                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2897                 return;
2898         }
2899         for (x=0;x<MAX_SLAVES;x++) {
2900                 if (!master->slaves[x]) {
2901                         master->slaves[x] = slave;
2902                         break;
2903                 }
2904         }
2905         if (x >= MAX_SLAVES) {
2906                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2907                 master->slaves[MAX_SLAVES - 1] = slave;
2908         }
2909         if (slave->master) 
2910                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2911         slave->master = master;
2912         
2913         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2914 }
2915
2916 static void disable_dtmf_detect(struct zt_pvt *p)
2917 {
2918         int val;
2919
2920         p->ignoredtmf = 1;
2921
2922 #ifdef ZT_TONEDETECT
2923         val = 0;
2924         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
2925 #endif          
2926         
2927 }
2928
2929 static void enable_dtmf_detect(struct zt_pvt *p)
2930 {
2931         int val;
2932
2933         p->ignoredtmf = 0;
2934
2935 #ifdef ZT_TONEDETECT
2936         val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
2937         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
2938 #endif          
2939 }
2940
2941 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)
2942 {
2943         struct ast_channel *who;
2944         struct zt_pvt *p0, *p1, *op0, *op1;
2945         struct zt_pvt *master = NULL, *slave = NULL;
2946         struct ast_frame *f;
2947         int to;
2948         int inconf = 0;
2949         int nothingok = 1;
2950         int ofd0, ofd1;
2951         int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
2952         int os0 = -1, os1 = -1;
2953         int priority = 0;
2954         struct ast_channel *oc0, *oc1;
2955         enum ast_bridge_result res;
2956
2957 #ifdef PRI_2BCT
2958         int triedtopribridge = 0;
2959         q931_call *q931c0 = NULL, *q931c1 = NULL;
2960 #endif
2961
2962         /* For now, don't attempt to native bridge if either channel needs DTMF detection.
2963            There is code below to handle it properly until DTMF is actually seen,
2964            but due to currently unresolved issues it's ignored...
2965         */
2966
2967         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2968                 return AST_BRIDGE_FAILED_NOWARN;
2969
2970         ast_mutex_lock(&c0->lock);
2971         ast_mutex_lock(&c1->lock);
2972
2973         p0 = c0->tech_pvt;
2974         p1 = c1->tech_pvt;
2975         /* cant do pseudo-channels here */
2976         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2977                 ast_mutex_unlock(&c0->lock);
2978                 ast_mutex_unlock(&c1->lock);
2979                 return AST_BRIDGE_FAILED_NOWARN;
2980         }
2981
2982         oi0 = zt_get_index(c0, p0, 0);
2983         oi1 = zt_get_index(c1, p1, 0);
2984         if ((oi0 < 0) || (oi1 < 0)) {
2985                 ast_mutex_unlock(&c0->lock);
2986                 ast_mutex_unlock(&c1->lock);
2987                 return AST_BRIDGE_FAILED;
2988         }
2989
2990         op0 = p0 = c0->tech_pvt;
2991         op1 = p1 = c1->tech_pvt;
2992         ofd0 = c0->fds[0];
2993         ofd1 = c1->fds[0];
2994         oc0 = p0->owner;
2995         oc1 = p1->owner;
2996
2997         ast_mutex_lock(&p0->lock);
2998         if (ast_mutex_trylock(&p1->lock)) {
2999                 /* Don't block, due to potential for deadlock */
3000                 ast_mutex_unlock(&p0->lock);
3001                 ast_mutex_unlock(&c0->lock);
3002                 ast_mutex_unlock(&c1->lock);
3003                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
3004                 return AST_BRIDGE_RETRY;
3005         }
3006
3007         if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
3008                 if (p0->owner && p1->owner) {
3009                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
3010                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
3011                                 master = p0;
3012                                 slave = p1;
3013                                 inconf = 1;
3014                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
3015                                 master = p1;
3016                                 slave = p0;
3017                                 inconf = 1;
3018                         } else {
3019                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
3020                                 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
3021                                         p0->channel,
3022                                         oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3023                                         p0->subs[SUB_REAL].inthreeway, p0->channel,
3024                                         oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
3025                                         p1->subs[SUB_REAL].inthreeway);
3026            &