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