6c93e6439a26f30cd5ad1d51ac64ff85b6efdda4
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Zaptel Pseudo TDM interface 
5  * 
6  * Copyright (C) 2003 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <string.h>
16 #include <sys/signal.h>
17 #include <errno.h>
18 #include <stdlib.h>
19 #if !defined(SOLARIS) && !defined(__FreeBSD__)
20 #include <stdint.h>
21 #endif
22 #include <unistd.h>
23 #include <sys/ioctl.h>
24 #ifdef __linux__
25 #include <linux/zaptel.h>
26 #else
27 #include <zaptel.h>
28 #endif /* __linux__ */
29 #include <math.h>
30 #include <tonezone.h>
31 #include <ctype.h>
32 #ifdef ZAPATA_PRI
33 #include <libpri.h>
34 #ifndef PRI_CALLINGPLANRDNIS
35 #error "You need newer libpri"
36 #endif
37 #endif
38 #ifdef ZAPATA_R2
39 #include <libmfcr2.h>
40 #endif
41
42 #include "asterisk.h"
43
44 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45
46 #include "asterisk/lock.h"
47 #include "asterisk/channel.h"
48 #include "asterisk/config.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/module.h"
51 #include "asterisk/pbx.h"
52 #include "asterisk/options.h"
53 #include "asterisk/file.h"
54 #include "asterisk/ulaw.h"
55 #include "asterisk/alaw.h"
56 #include "asterisk/callerid.h"
57 #include "asterisk/adsi.h"
58 #include "asterisk/cli.h"
59 #include "asterisk/cdr.h"
60 #include "asterisk/features.h"
61 #include "asterisk/musiconhold.h"
62 #include "asterisk/say.h"
63 #include "asterisk/tdd.h"
64 #include "asterisk/app.h"
65 #include "asterisk/dsp.h"
66 #include "asterisk/astdb.h"
67 #include "asterisk/manager.h"
68 #include "asterisk/causes.h"
69 #include "asterisk/term.h"
70 #include "asterisk/utils.h"
71 #include "asterisk/transcap.h"
72
73 #ifndef ZT_SIG_EM_E1
74 #error "Your zaptel is too old.  please cvs update"
75 #endif
76
77 #ifndef ZT_TONEDETECT
78 /* Work around older code with no tone detect */
79 #define ZT_EVENT_DTMFDOWN 0
80 #define ZT_EVENT_DTMFUP 0
81 #endif
82
83 /*
84  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
85  * the user hangs up to reset the state machine so ring works properly.
86  * This is used to be able to support kewlstart by putting the zhone in
87  * groundstart mode since their forward disconnect supervision is entirely
88  * broken even though their documentation says it isn't and their support
89  * is entirely unwilling to provide any assistance with their channel banks
90  * even though their web site says they support their products for life.
91  */
92
93 /* #define ZHONE_HACK */
94
95 /*
96  * Define if you want to check the hook state for an FXO (FXS signalled) interface
97  * before dialing on it.  Certain FXO interfaces always think they're out of
98  * service with this method however.
99  */
100 /* #define ZAP_CHECK_HOOKSTATE */
101
102 /* Typically, how many rings before we should send Caller*ID */
103 #define DEFAULT_CIDRINGS 1
104
105 #define CHANNEL_PSEUDO -12
106
107 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
108
109 /* Signaling types that need to use MF detection should be placed in this macro */
110 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FEATB)) 
111
112 static const char desc[] = "Zapata Telephony"
113 #ifdef ZAPATA_PRI
114                " w/PRI"
115 #endif
116 #ifdef ZAPATA_R2
117                " w/R2"
118 #endif
119 ;
120
121 static const char tdesc[] = "Zapata Telephony Driver"
122 #ifdef ZAPATA_PRI
123                " w/PRI"
124 #endif
125 #ifdef ZAPATA_R2
126                " w/R2"
127 #endif
128 ;
129
130 static const char type[] = "Zap";
131 static const char config[] = "zapata.conf";
132
133 #define SIG_EM          ZT_SIG_EM
134 #define SIG_EMWINK      (0x100000 | ZT_SIG_EM)
135 #define SIG_FEATD       (0x200000 | ZT_SIG_EM)
136 #define SIG_FEATDMF     (0x400000 | ZT_SIG_EM)
137 #define SIG_FEATB       (0x800000 | ZT_SIG_EM)
138 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
139 #define SIG_FEATDMF_TA  (0x2000000 | ZT_SIG_EM)
140 #define SIG_FXSLS       ZT_SIG_FXSLS
141 #define SIG_FXSGS       ZT_SIG_FXSGS
142 #define SIG_FXSKS       ZT_SIG_FXSKS
143 #define SIG_FXOLS       ZT_SIG_FXOLS
144 #define SIG_FXOGS       ZT_SIG_FXOGS
145 #define SIG_FXOKS       ZT_SIG_FXOKS
146 #define SIG_PRI         ZT_SIG_CLEAR
147 #define SIG_R2          ZT_SIG_CAS
148 #define SIG_SF          ZT_SIG_SF
149 #define SIG_SFWINK      (0x100000 | ZT_SIG_SF)
150 #define SIG_SF_FEATD    (0x200000 | ZT_SIG_SF)
151 #define SIG_SF_FEATDMF  (0x400000 | ZT_SIG_SF)
152 #define SIG_SF_FEATB    (0x800000 | ZT_SIG_SF)
153 #define SIG_EM_E1       ZT_SIG_EM_E1
154 #define SIG_GR303FXOKS   (0x100000 | ZT_SIG_FXOKS)
155 #define SIG_GR303FXSKS   (0x200000 | ZT_SIG_FXSKS)
156
157 #define NUM_SPANS               32
158 #define NUM_DCHANS              4               /* No more than 4 d-channels */
159 #define MAX_CHANNELS    672             /* No more than a DS3 per trunk group */
160
161 #define CHAN_PSEUDO     -2
162
163 #define DCHAN_PROVISIONED (1 << 0)
164 #define DCHAN_NOTINALARM  (1 << 1)
165 #define DCHAN_UP          (1 << 2)
166
167 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
168
169 static char context[AST_MAX_CONTEXT] = "default";
170 static char cid_num[256] = "";
171 static char cid_name[256] = "";
172 static char defaultcic[64] = "";
173 static char defaultozz[64] = "";
174
175 static char language[MAX_LANGUAGE] = "";
176 static char musicclass[MAX_MUSICCLASS] = "";
177 static char progzone[10]= "";
178
179 static int usedistinctiveringdetection = 0;
180
181 static int transfertobusy = 1;
182
183 static int use_callerid = 1;
184 static int cid_signalling = CID_SIG_BELL;
185 static int cid_start = CID_START_RING;
186 static int zaptrcallerid = 0;
187 static int cur_signalling = -1;
188
189 static ast_group_t cur_group = 0;
190 static ast_group_t cur_callergroup = 0;
191 static ast_group_t cur_pickupgroup = 0;
192 static int relaxdtmf = 0;
193
194 static int immediate = 0;
195
196 static int stripmsd = 0;
197
198 static int callwaiting = 0;
199
200 static int callwaitingcallerid = 0;
201
202 static int hidecallerid = 0;
203
204 static int restrictcid = 0;
205
206 static int use_callingpres = 0;
207
208 static int callreturn = 0;
209
210 static int threewaycalling = 0;
211
212 static int transfer = 0;
213
214 static int canpark = 0;
215
216 static int cancallforward = 0;
217
218 static float rxgain = 0.0;
219
220 static float txgain = 0.0;
221
222 static int tonezone = -1;
223
224 static int echocancel;
225
226 static int echotraining;
227
228 static int pulse;
229
230 static int echocanbridged = 0;
231
232 static int busydetect = 0;
233
234 static int busycount = 3;
235 static int busy_tonelength = 0;
236 static int busy_quietlength = 0;
237
238 static int callprogress = 0;
239
240 static char accountcode[AST_MAX_ACCOUNT_CODE] = "";
241
242 static char mailbox[AST_MAX_EXTENSION];
243
244 static int amaflags = 0;
245
246 static int adsi = 0;
247
248 static int numbufs = 4;
249
250 static int cur_prewink = -1;
251 static int cur_preflash = -1;
252 static int cur_wink = -1;
253 static int cur_flash = -1;
254 static int cur_start = -1;
255 static int cur_rxwink = -1;
256 static int cur_rxflash = -1;
257 static int cur_debounce = -1;
258 static int cur_priexclusive = 0;
259
260 static int priindication_oob = 0;
261
262 #ifdef ZAPATA_PRI
263 static int minunused = 2;
264 static int minidle = 0;
265 static char idleext[AST_MAX_EXTENSION];
266 static char idledial[AST_MAX_EXTENSION];
267 static int overlapdial = 0;
268 static int facilityenable = 0;
269 static char internationalprefix[10] = "";
270 static char nationalprefix[10] = "";
271 static char localprefix[20] = "";
272 static char privateprefix[20] = "";
273 static char unknownprefix[20] = "";
274 static long resetinterval = 3600;                       /* How often (in seconds) to reset unused channels. Default 1 hour. */
275 static struct ast_channel inuse = { "GR-303InUse" };
276 #ifdef PRI_GETSET_TIMERS
277 static int pritimers[PRI_MAX_TIMERS];
278 #endif
279 static int pridebugfd = -1;
280 static char pridebugfilename[1024]="";
281 #endif
282
283 /* Wait up to 16 seconds for first digit (FXO logic) */
284 static int firstdigittimeout = 16000;
285
286 /* How long to wait for following digits (FXO logic) */
287 static int gendigittimeout = 8000;
288
289 /* How long to wait for an extra digit, if there is an ambiguous match */
290 static int matchdigittimeout = 3000;
291
292 static int usecnt =0;
293 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
294
295 /* Protect the interface list (of zt_pvt's) */
296 AST_MUTEX_DEFINE_STATIC(iflock);
297
298
299 static int ifcount = 0;
300
301 #ifdef ZAPATA_PRI
302 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
303 #endif
304
305 /* Whether we answer on a Polarity Switch event */
306 static int answeronpolarityswitch = 0;
307
308 /* Whether we hang up on a Polarity Switch event */
309 static int hanguponpolarityswitch = 0;
310
311 /* How long (ms) to ignore Polarity Switch events after we answer a call */
312 static int polarityonanswerdelay = 600;
313
314 /* When to send the CallerID signals (rings) */
315 static int sendcalleridafter = DEFAULT_CIDRINGS;
316
317 /* Protect the monitoring thread, so only one process can kill or start it, and not
318    when it's doing something critical. */
319 AST_MUTEX_DEFINE_STATIC(monlock);
320
321 /* This is the thread for the monitor which checks for input on the channels
322    which are not currently in use.  */
323 static pthread_t monitor_thread = AST_PTHREADT_NULL;
324
325 static int restart_monitor(void);
326
327 static enum ast_bridge_result zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
328
329 static int zt_sendtext(struct ast_channel *c, const char *text);
330
331 static inline int zt_get_event(int fd)
332 {
333         /* Avoid the silly zt_getevent which ignores a bunch of events */
334         int j;
335         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
336         return j;
337 }
338
339 static inline int zt_wait_event(int fd)
340 {
341         /* Avoid the silly zt_waitevent which ignores a bunch of events */
342         int i,j=0;
343         i = ZT_IOMUX_SIGEVENT;
344         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
345         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
346         return j;
347 }
348
349 /* Chunk size to read -- we use 20ms chunks to make things happy.  */   
350 #define READ_SIZE 160
351
352 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
353 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
354
355 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
356 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
357 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /* 500 ms */
358 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /* 2000 ms */
359 #define DEFAULT_RINGT                           ( (8000 * 8) / READ_SIZE)
360
361 struct zt_pvt;
362
363
364 #ifdef ZAPATA_R2
365 static int r2prot = -1;
366 #endif
367
368 static int ringt_base = DEFAULT_RINGT;
369
370 #ifdef ZAPATA_PRI
371
372 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
373 #define PRI_CHANNEL(p) ((p) & 0xff)
374 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
375 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
376
377 struct zt_pri {
378         pthread_t master;                                               /* Thread of master */
379         ast_mutex_t lock;                                               /* Mutex */
380         char idleext[AST_MAX_EXTENSION];                                /* Where to idle extra calls */
381         char idlecontext[AST_MAX_CONTEXT];                              /* What context to use for idle */
382         char idledial[AST_MAX_EXTENSION];                               /* What to dial before dumping */
383         int minunused;                                                  /* Min # of channels to keep empty */
384         int minidle;                                                    /* Min # of "idling" calls to keep active */
385         int nodetype;                                                   /* Node type */
386         int switchtype;                                                 /* Type of switch to emulate */
387         int nsf;                                                        /* Network-Specific Facilities */
388         int dialplan;                                                   /* Dialing plan */
389         int localdialplan;                                              /* Local dialing plan */
390         char internationalprefix[10];                                   /* country access code ('00' for european dialplans) */
391         char nationalprefix[10];                                        /* area access code ('0' for european dialplans) */
392         char localprefix[20];                                           /* area access code + area code ('0'+area code for european dialplans) */
393         char privateprefix[20];                                         /* for private dialplans */
394         char unknownprefix[20];                                         /* for unknown dialplans */
395         int dchannels[NUM_DCHANS];                                      /* What channel are the dchannels on */
396         int trunkgroup;                                                 /* What our trunkgroup is */
397         int mastertrunkgroup;                                           /* What trunk group is our master */
398         int prilogicalspan;                                             /* Logical span number within trunk group */
399         int numchans;                                                   /* Num of channels we represent */
400         int overlapdial;                                                /* In overlap dialing mode */
401         int facilityenable;                                             /* Enable facility IEs */
402         struct pri *dchans[NUM_DCHANS];                                 /* Actual d-channels */
403         int dchanavail[NUM_DCHANS];                                     /* Whether each channel is available */
404         struct pri *pri;                                                /* Currently active D-channel */
405         int debug;
406         int fds[NUM_DCHANS];                                            /* FD's for d-channels */
407         int offset;
408         int span;
409         int resetting;
410         int resetpos;
411         time_t lastreset;                                               /* time when unused channels were last reset */
412         long resetinterval;                                             /* Interval (in seconds) for resetting unused channels */
413         struct zt_pvt *pvts[MAX_CHANNELS];                              /* Member channel pvt structs */
414         struct zt_pvt *crvs;                                            /* Member CRV structs */
415         struct zt_pvt *crvend;                                          /* Pointer to end of CRV structs */
416 };
417
418
419 static struct zt_pri pris[NUM_SPANS];
420
421 static int pritype = PRI_CPE;
422
423 #if 0
424 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
425 #else
426 #define DEFAULT_PRI_DEBUG 0
427 #endif
428
429 static inline void pri_rel(struct zt_pri *pri)
430 {
431         ast_mutex_unlock(&pri->lock);
432 }
433
434 static int switchtype = PRI_SWITCH_NI2;
435 static int nsf = PRI_NSF_NONE;
436 static int dialplan = PRI_NATIONAL_ISDN + 1;
437 static int localdialplan = PRI_NATIONAL_ISDN + 1;
438
439 #else
440 /* Shut up the compiler */
441 struct zt_pri;
442 #endif
443
444 #define SUB_REAL                0                       /* Active call */
445 #define SUB_CALLWAIT    1                       /* Call-Waiting call on hold */
446 #define SUB_THREEWAY    2                       /* Three-way call */
447
448 /* Polarity states */
449 #define POLARITY_IDLE   0
450 #define POLARITY_REV    1
451
452
453 static struct zt_distRings drings;
454
455 struct distRingData {
456         int ring[3];
457 };
458 struct ringContextData {
459         char contextData[AST_MAX_CONTEXT];
460 };
461 struct zt_distRings {
462         struct distRingData ringnum[3];
463         struct ringContextData ringContext[3];
464 };
465
466 static char *subnames[] = {
467         "Real",
468         "Callwait",
469         "Threeway"
470 };
471
472 struct zt_subchannel {
473         int zfd;
474         struct ast_channel *owner;
475         int chan;
476         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
477         struct ast_frame f;             /* One frame for each channel.  How did this ever work before? */
478         unsigned int needringing:1;
479         unsigned int needbusy:1;
480         unsigned int needcongestion:1;
481         unsigned int needcallerid:1;
482         unsigned int needanswer:1;
483         unsigned int needflash:1;
484         unsigned int linear:1;
485         unsigned int inthreeway:1;
486         ZT_CONFINFO curconf;
487 };
488
489 #define CONF_USER_REAL          (1 << 0)
490 #define CONF_USER_THIRDCALL     (1 << 1)
491
492 #define MAX_SLAVES      4
493
494 static struct zt_pvt {
495         ast_mutex_t lock;
496         struct ast_channel *owner;                      /* Our current active owner (if applicable) */
497                                                         /* Up to three channels can be associated with this call */
498                 
499         struct zt_subchannel sub_unused;                /* Just a safety precaution */
500         struct zt_subchannel subs[3];                   /* Sub-channels */
501         struct zt_confinfo saveconf;                    /* Saved conference info */
502
503         struct zt_pvt *slaves[MAX_SLAVES];              /* Slave to us (follows our conferencing) */
504         struct zt_pvt *master;                          /* Master to us (we follow their conferencing) */
505         int inconference;                               /* If our real should be in the conference */
506         
507         int sig;                                        /* Signalling style */
508         int radio;                                      /* radio type */
509         float rxgain;
510         float txgain;
511         int tonezone;                                   /* tone zone for this chan, or -1 for default */
512         struct zt_pvt *next;                            /* Next channel in list */
513         struct zt_pvt *prev;                            /* Prev channel in list */
514
515         /* flags */
516         unsigned int adsi:1;
517         unsigned int answeronpolarityswitch:1;
518         unsigned int busydetect:1;
519         unsigned int callreturn:1;
520         unsigned int callwaiting:1;
521         unsigned int callwaitingcallerid:1;
522         unsigned int cancallforward:1;
523         unsigned int canpark:1;
524         unsigned int confirmanswer:1;                   /* Wait for '#' to confirm answer */
525         unsigned int destroy:1;
526         unsigned int didtdd:1;                          /* flag to say its done it once */
527         unsigned int dialednone:1;
528         unsigned int dialing:1;
529         unsigned int digital:1;
530         unsigned int dnd:1;
531         unsigned int echobreak:1;
532         unsigned int echocanbridged:1;
533         unsigned int echocanon:1;
534         unsigned int faxhandled:1;                      /* Has a fax tone already been handled? */
535         unsigned int firstradio:1;
536         unsigned int hanguponpolarityswitch:1;
537         unsigned int hardwaredtmf:1;
538         unsigned int hidecallerid;
539         unsigned int ignoredtmf:1;
540         unsigned int immediate:1;                       /* Answer before getting digits? */
541         unsigned int inalarm:1;
542         unsigned int mate:1;                            /* flag to say its in MATE mode */
543         unsigned int outgoing:1;
544         unsigned int overlapdial:1;
545         unsigned int permcallwaiting:1;
546         unsigned int permhidecallerid:1;                /* Whether to hide our outgoing caller ID or not */
547         unsigned int priindication_oob:1;
548         unsigned int priexclusive:1;
549         unsigned int pulse:1;
550         unsigned int pulsedial:1;                       /* whether a pulse dial phone is detected */
551         unsigned int restrictcid:1;                     /* Whether restrict the callerid -> only send ANI */
552         unsigned int threewaycalling:1;
553         unsigned int transfer:1;
554         unsigned int use_callerid:1;                    /* Whether or not to use caller id on this channel */
555         unsigned int use_callingpres:1;                 /* Whether to use the callingpres the calling switch sends */
556         unsigned int usedistinctiveringdetection:1;
557         unsigned int zaptrcallerid:1;                   /* should we use the callerid from incoming call on zap transfer or not */
558         unsigned int transfertobusy:1;                  /* allow flash-transfers to busy channels */
559 #if defined(ZAPATA_PRI)
560         unsigned int alerting:1;
561         unsigned int alreadyhungup:1;
562         unsigned int isidlecall:1;
563         unsigned int resetting:1;
564         unsigned int setup_ack:1;
565 #endif
566 #if defined(ZAPATA_R2)
567         unsigned int hasr2call:1;
568         unsigned int r2blocked:1;
569         unsigned int sigchecked:1;
570 #endif
571
572         struct zt_distRings drings;
573
574         char context[AST_MAX_CONTEXT];
575         char defcontext[AST_MAX_CONTEXT];
576         char exten[AST_MAX_EXTENSION];
577         char language[MAX_LANGUAGE];
578         char musicclass[MAX_MUSICCLASS];
579 #ifdef PRI_ANI
580         char cid_ani[AST_MAX_EXTENSION];
581 #endif
582         char cid_num[AST_MAX_EXTENSION];
583         int cid_ton;                                    /* Type Of Number (TON) */
584         char cid_name[AST_MAX_EXTENSION];
585         char lastcid_num[AST_MAX_EXTENSION];
586         char lastcid_name[AST_MAX_EXTENSION];
587         char *origcid_num;                              /* malloced original callerid */
588         char *origcid_name;                             /* malloced original callerid */
589         char callwait_num[AST_MAX_EXTENSION];
590         char callwait_name[AST_MAX_EXTENSION];
591         char rdnis[AST_MAX_EXTENSION];
592         char dnid[AST_MAX_EXTENSION];
593         unsigned int group;
594         int law;
595         int confno;                                     /* Our conference */
596         int confusers;                                  /* Who is using our conference */
597         int propconfno;                                 /* Propagated conference number */
598         ast_group_t callgroup;
599         ast_group_t pickupgroup;
600         int channel;                                    /* Channel Number or CRV */
601         int span;                                       /* Span number */
602         time_t guardtime;                               /* Must wait this much time before using for new call */
603         int cid_signalling;                             /* CID signalling type bell202 or v23 */
604         int cid_start;                                  /* CID start indicator, polarity or ring */
605         int callingpres;                                /* The value of callling presentation that we're going to use when placing a PRI call */
606         int callwaitingrepeat;                          /* How many samples to wait before repeating call waiting */
607         int cidcwexpire;                                /* When to expire our muting for CID/CW */
608         unsigned char *cidspill;
609         int cidpos;
610         int cidlen;
611         int ringt;
612         int ringt_base;
613         int stripmsd;
614         int callwaitcas;
615         int callwaitrings;
616         int echocancel;
617         int echotraining;
618         char echorest[20];
619         int busycount;
620         int busy_tonelength;
621         int busy_quietlength;
622         int callprogress;
623         struct timeval flashtime;                       /* Last flash-hook time */
624         struct ast_dsp *dsp;
625         int cref;                                       /* Call reference number */
626         ZT_DIAL_OPERATION dop;
627         int whichwink;                                  /* SIG_FEATDMF_TA Which wink are we on? */
628         char finaldial[64];
629         char accountcode[AST_MAX_ACCOUNT_CODE];         /* Account code */
630         int amaflags;                                   /* AMA Flags */
631         struct tdd_state *tdd;                          /* TDD flag */
632         char call_forward[AST_MAX_EXTENSION];
633         char mailbox[AST_MAX_EXTENSION];
634         char dialdest[256];
635         int onhooktime;
636         int msgstate;
637         int distinctivering;                            /* Which distinctivering to use */
638         int cidrings;                                   /* Which ring to deliver CID on */
639         int dtmfrelax;                                  /* whether to run in relaxed DTMF mode */
640         int fake_event;
641         int polarityonanswerdelay;
642         struct timeval polaritydelaytv;
643         int sendcalleridafter;
644 #ifdef ZAPATA_PRI
645         struct zt_pri *pri;
646         struct zt_pvt *bearer;
647         struct zt_pvt *realcall;
648         q931_call *call;
649         int prioffset;
650         int logicalspan;
651         int proceeding;
652         int dsp_features;
653 #endif  
654 #ifdef ZAPATA_R2
655         int r2prot;
656         mfcr2_t *r2;
657 #endif  
658         int polarity;
659
660 } *iflist = NULL, *ifend = NULL;
661
662 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
663 static int zt_digit(struct ast_channel *ast, char digit);
664 static int zt_sendtext(struct ast_channel *c, const char *text);
665 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
666 static int zt_hangup(struct ast_channel *ast);
667 static int zt_answer(struct ast_channel *ast);
668 struct ast_frame *zt_read(struct ast_channel *ast);
669 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
670 struct ast_frame *zt_exception(struct ast_channel *ast);
671 static int zt_indicate(struct ast_channel *chan, int condition);
672 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
673 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
674
675 static const struct ast_channel_tech zap_tech = {
676         .type = type,
677         .description = tdesc,
678         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW,
679         .requester = zt_request,
680         .send_digit = zt_digit,
681         .send_text = zt_sendtext,
682         .call = zt_call,
683         .hangup = zt_hangup,
684         .answer = zt_answer,
685         .read = zt_read,
686         .write = zt_write,
687         .bridge = zt_bridge,
688         .exception = zt_exception,
689         .indicate = zt_indicate,
690         .fixup = zt_fixup,
691         .setoption = zt_setoption,
692 };
693
694 #ifdef ZAPATA_PRI
695 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
696 #else
697 #define GET_CHANNEL(p) ((p)->channel)
698 #endif
699
700 struct zt_pvt *round_robin[32];
701
702 #ifdef ZAPATA_PRI
703 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
704 {
705         int res;
706         /* Grab the lock first */
707         do {
708             res = ast_mutex_trylock(&pri->lock);
709                 if (res) {
710                         ast_mutex_unlock(&pvt->lock);
711                         /* Release the lock and try again */
712                         usleep(1);
713                         ast_mutex_lock(&pvt->lock);
714                 }
715         } while(res);
716         /* Then break the poll */
717         pthread_kill(pri->master, SIGURG);
718         return 0;
719 }
720 #endif
721
722 #define NUM_CADENCE_MAX 25
723 static int num_cadence = 4;
724 static int user_has_defined_cadences = 0;
725
726 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
727         { { 125, 125, 2000, 4000 } },                   /* Quick chirp followed by normal ring */
728         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /* British style ring */
729         { { 125, 125, 125, 125, 125, 4000 } },  /* Three short bursts */
730         { { 1000, 500, 2500, 5000 } },  /* Long ring */
731 };
732
733 int receivedRingT; /* Used to find out what ringtone we are on */
734
735 /* cidrings says in which pause to transmit the cid information, where the first pause
736  * is 1, the second pause is 2 and so on.
737  */
738
739 static int cidrings[NUM_CADENCE_MAX] = {
740         2,                                                                              /* Right after first long ring */
741         4,                                                                              /* Right after long part */
742         3,                                                                              /* After third chirp */
743         2,                                                                              /* Second spell */
744 };
745
746 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
747                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
748
749 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
750 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
751
752 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
753 {
754         int res;
755         if (p->subs[0].owner == ast)
756                 res = 0;
757         else if (p->subs[1].owner == ast)
758                 res = 1;
759         else if (p->subs[2].owner == ast)
760                 res = 2;
761         else {
762                 res = -1;
763                 if (!nullok)
764                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
765         }
766         return res;
767 }
768
769 #ifdef ZAPATA_PRI
770 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
771 #else
772 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
773 #endif
774 {
775         struct ast_frame null = { AST_FRAME_NULL, };
776 #ifdef ZAPATA_PRI
777         if (pri)
778                 ast_mutex_unlock(&pri->lock);
779 #endif                  
780         for (;;) {
781                 if (p->subs[a].owner) {
782                         if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
783                                 ast_mutex_unlock(&p->lock);
784                                 usleep(1);
785                                 ast_mutex_lock(&p->lock);
786                         } else {
787                                 ast_queue_frame(p->subs[a].owner, &null);
788                                 ast_mutex_unlock(&p->subs[a].owner->lock);
789                                 break;
790                         }
791                 } else
792                         break;
793         }
794 #ifdef ZAPATA_PRI
795         if (pri)
796                 ast_mutex_lock(&pri->lock);
797 #endif                  
798 }
799
800 #ifdef ZAPATA_PRI
801 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
802 #else
803 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
804 #endif
805 {
806         /* We must unlock the PRI to avoid the possibility of a deadlock */
807 #ifdef ZAPATA_PRI
808         if (pri)
809                 ast_mutex_unlock(&pri->lock);
810 #endif          
811         for (;;) {
812                 if (p->owner) {
813                         if (ast_mutex_trylock(&p->owner->lock)) {
814                                 ast_mutex_unlock(&p->lock);
815                                 usleep(1);
816                                 ast_mutex_lock(&p->lock);
817                         } else {
818                                 ast_queue_frame(p->owner, f);
819                                 ast_mutex_unlock(&p->owner->lock);
820                                 break;
821                         }
822                 } else
823                         break;
824         }
825 #ifdef ZAPATA_PRI
826         if (pri)
827                 ast_mutex_lock(&pri->lock);
828 #endif          
829 }
830
831 static int restore_gains(struct zt_pvt *p);
832
833 static void swap_subs(struct zt_pvt *p, int a, int b)
834 {
835         int tchan;
836         int tinthreeway;
837         struct ast_channel *towner;
838
839         ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
840
841         tchan = p->subs[a].chan;
842         towner = p->subs[a].owner;
843         tinthreeway = p->subs[a].inthreeway;
844
845         p->subs[a].chan = p->subs[b].chan;
846         p->subs[a].owner = p->subs[b].owner;
847         p->subs[a].inthreeway = p->subs[b].inthreeway;
848
849         p->subs[b].chan = tchan;
850         p->subs[b].owner = towner;
851         p->subs[b].inthreeway = tinthreeway;
852
853         if (p->subs[a].owner) 
854                 p->subs[a].owner->fds[0] = p->subs[a].zfd;
855         if (p->subs[b].owner) 
856                 p->subs[b].owner->fds[0] = p->subs[b].zfd;
857         wakeup_sub(p, a, NULL);
858         wakeup_sub(p, b, NULL);
859 }
860
861 static int zt_open(char *fn)
862 {
863         int fd;
864         int isnum;
865         int chan = 0;
866         int bs;
867         int x;
868         isnum = 1;
869         for (x=0;x<strlen(fn);x++) {
870                 if (!isdigit(fn[x])) {
871                         isnum = 0;
872                         break;
873                 }
874         }
875         if (isnum) {
876                 chan = atoi(fn);
877                 if (chan < 1) {
878                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
879                         return -1;
880                 }
881                 fn = "/dev/zap/channel";
882         }
883         fd = open(fn, O_RDWR | O_NONBLOCK);
884         if (fd < 0) {
885                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
886                 return -1;
887         }
888         if (chan) {
889                 if (ioctl(fd, ZT_SPECIFY, &chan)) {
890                         x = errno;
891                         close(fd);
892                         errno = x;
893                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
894                         return -1;
895                 }
896         }
897         bs = READ_SIZE;
898         if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
899         return fd;
900 }
901
902 static void zt_close(int fd)
903 {
904         if(fd > 0)
905                 close(fd);
906 }
907
908 int zt_setlinear(int zfd, int linear)
909 {
910         int res;
911         res = ioctl(zfd, ZT_SETLINEAR, &linear);
912         if (res)
913                 return res;
914         return 0;
915 }
916
917
918 int zt_setlaw(int zfd, int law)
919 {
920         int res;
921         res = ioctl(zfd, ZT_SETLAW, &law);
922         if (res)
923                 return res;
924         return 0;
925 }
926
927 static int alloc_sub(struct zt_pvt *p, int x)
928 {
929         ZT_BUFFERINFO bi;
930         int res;
931         if (p->subs[x].zfd < 0) {
932                 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
933                 if (p->subs[x].zfd > -1) {
934                         res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
935                         if (!res) {
936                                 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
937                                 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
938                                 bi.numbufs = numbufs;
939                                 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
940                                 if (res < 0) {
941                                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
942                                 }
943                         } else 
944                                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
945                         if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
946                                 ast_log(LOG_WARNING,"Unable to get channel number for pseudo channel on FD %d\n",p->subs[x].zfd);
947                                 zt_close(p->subs[x].zfd);
948                                 p->subs[x].zfd = -1;
949                                 return -1;
950                         }
951                         if (option_debug)
952                                 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
953                         return 0;
954                 } else
955                         ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
956                 return -1;
957         }
958         ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
959         return -1;
960 }
961
962 static int unalloc_sub(struct zt_pvt *p, int x)
963 {
964         if (!x) {
965                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
966                 return -1;
967         }
968         ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
969         if (p->subs[x].zfd > -1) {
970                 zt_close(p->subs[x].zfd);
971         }
972         p->subs[x].zfd = -1;
973         p->subs[x].linear = 0;
974         p->subs[x].chan = 0;
975         p->subs[x].owner = NULL;
976         p->subs[x].inthreeway = 0;
977         p->polarity = POLARITY_IDLE;
978         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
979         return 0;
980 }
981
982 static int zt_digit(struct ast_channel *ast, char digit)
983 {
984         ZT_DIAL_OPERATION zo;
985         struct zt_pvt *p;
986         int res = 0;
987         int index;
988         p = ast->tech_pvt;
989         ast_mutex_lock(&p->lock);
990         index = zt_get_index(ast, p, 0);
991         if ((index == SUB_REAL) && p->owner) {
992 #ifdef ZAPATA_PRI
993                 if (p->sig == SIG_PRI && ast->_state == AST_STATE_DIALING && (p->proceeding < 2)) {
994                         if (p->setup_ack) {
995                                 if (!pri_grab(p, p->pri)) {
996                                         pri_information(p->pri->pri,p->call,digit);
997                                         pri_rel(p->pri);
998                                 } else
999                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1000                         } else if (strlen(p->dialdest) < sizeof(p->dialdest) - 1) {
1001                                 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1002                                 res = strlen(p->dialdest);
1003                                 p->dialdest[res++] = digit;
1004                                 p->dialdest[res] = '\0';
1005                         }
1006                 } else {
1007 #else
1008                 {
1009 #endif
1010                         zo.op = ZT_DIAL_OP_APPEND;
1011                         zo.dialstr[0] = 'T';
1012                         zo.dialstr[1] = digit;
1013                         zo.dialstr[2] = 0;
1014                         if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1015                                 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1016                         else
1017                                 p->dialing = 1;
1018                 }
1019         }
1020         ast_mutex_unlock(&p->lock);
1021         return res;
1022 }
1023
1024 static char *events[] = {
1025                 "No event",
1026                 "On hook",
1027                 "Ring/Answered",
1028                 "Wink/Flash",
1029                 "Alarm",
1030                 "No more alarm",
1031                 "HDLC Abort",
1032                 "HDLC Overrun",
1033                 "HDLC Bad FCS",
1034                 "Dial Complete",
1035                 "Ringer On",
1036                 "Ringer Off",
1037                 "Hook Transition Complete",
1038                 "Bits Changed",
1039                 "Pulse Start",
1040                 "Timer Expired",
1041                 "Timer Ping",
1042                 "Polarity Reversal",
1043                 "Ring Begin",
1044 };
1045
1046 static struct {
1047         int alarm;
1048         char *name;
1049 } alarms[] = {
1050         { ZT_ALARM_RED, "Red Alarm" },
1051         { ZT_ALARM_YELLOW, "Yellow Alarm" },
1052         { ZT_ALARM_BLUE, "Blue Alarm" },
1053         { ZT_ALARM_RECOVER, "Recovering" },
1054         { ZT_ALARM_LOOPBACK, "Loopback" },
1055         { ZT_ALARM_NOTOPEN, "Not Open" },
1056         { ZT_ALARM_NONE, "None" },
1057 };
1058
1059 static char *alarm2str(int alarm)
1060 {
1061         int x;
1062         for (x=0;x<sizeof(alarms) / sizeof(alarms[0]); x++) {
1063                 if (alarms[x].alarm & alarm)
1064                         return alarms[x].name;
1065         }
1066         return alarm ? "Unknown Alarm" : "No Alarm";
1067 }
1068
1069 static char *event2str(int event)
1070 {
1071         static char buf[256];
1072         if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1073                 return events[event];
1074         sprintf(buf, "Event %d", event); /* safe */
1075         return buf;
1076 }
1077
1078 #ifdef ZAPATA_PRI
1079 static char *dialplan2str(int dialplan)
1080 {
1081         if (dialplan == -1) {
1082                 return("Dynamically set dialplan in ISDN");
1083         }
1084         return(pri_plan2str(dialplan));
1085 }
1086 #endif
1087
1088 #ifdef ZAPATA_R2
1089 static int str2r2prot(char *swtype)
1090 {
1091     if (!strcasecmp(swtype, "ar"))
1092         return MFCR2_PROT_ARGENTINA;
1093     /*endif*/
1094     if (!strcasecmp(swtype, "cn"))
1095         return MFCR2_PROT_CHINA;
1096     /*endif*/
1097     if (!strcasecmp(swtype, "kr"))
1098         return MFCR2_PROT_KOREA;
1099     /*endif*/
1100     return -1;
1101 }
1102 #endif
1103
1104 static char *zap_sig2str(int sig)
1105 {
1106         static char buf[256];
1107         switch(sig) {
1108         case SIG_EM:
1109                 return "E & M Immediate";
1110         case SIG_EMWINK:
1111                 return "E & M Wink";
1112         case SIG_EM_E1:
1113                 return "E & M E1";
1114         case SIG_FEATD:
1115                 return "Feature Group D (DTMF)";
1116         case SIG_FEATDMF:
1117                 return "Feature Group D (MF)";
1118         case SIG_FEATDMF_TA:
1119                 return "Feature Groud D (MF) Tandem Access";
1120         case SIG_FEATB:
1121                 return "Feature Group B (MF)";
1122         case SIG_E911:
1123                 return "E911 (MF)";
1124         case SIG_FXSLS:
1125                 return "FXS Loopstart";
1126         case SIG_FXSGS:
1127                 return "FXS Groundstart";
1128         case SIG_FXSKS:
1129                 return "FXS Kewlstart";
1130         case SIG_FXOLS:
1131                 return "FXO Loopstart";
1132         case SIG_FXOGS:
1133                 return "FXO Groundstart";
1134         case SIG_FXOKS:
1135                 return "FXO Kewlstart";
1136         case SIG_PRI:
1137                 return "PRI Signalling";
1138         case SIG_R2:
1139                 return "R2 Signalling";
1140         case SIG_SF:
1141                 return "SF (Tone) Signalling Immediate";
1142         case SIG_SFWINK:
1143                 return "SF (Tone) Signalling Wink";
1144         case SIG_SF_FEATD:
1145                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1146         case SIG_SF_FEATDMF:
1147                 return "SF (Tone) Signalling with Feature Group D (MF)";
1148         case SIG_SF_FEATB:
1149                 return "SF (Tone) Signalling with Feature Group B (MF)";
1150         case SIG_GR303FXOKS:
1151                 return "GR-303 Signalling with FXOKS";
1152         case SIG_GR303FXSKS:
1153                 return "GR-303 Signalling with FXSKS";
1154         case 0:
1155                 return "Pseudo Signalling";
1156         default:
1157                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1158                 return buf;
1159         }
1160 }
1161
1162 #define sig2str zap_sig2str
1163
1164 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1165 {
1166         /* If the conference already exists, and we're already in it
1167            don't bother doing anything */
1168         ZT_CONFINFO zi;
1169         
1170         memset(&zi, 0, sizeof(zi));
1171         zi.chan = 0;
1172
1173         if (slavechannel > 0) {
1174                 /* If we have only one slave, do a digital mon */
1175                 zi.confmode = ZT_CONF_DIGITALMON;
1176                 zi.confno = slavechannel;
1177         } else {
1178                 if (!index) {
1179                         /* Real-side and pseudo-side both participate in conference */
1180                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1181                                                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1182                 } else
1183                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1184                 zi.confno = p->confno;
1185         }
1186         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1187                 return 0;
1188         if (c->zfd < 0)
1189                 return 0;
1190         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1191                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1192                 return -1;
1193         }
1194         if (slavechannel < 1) {
1195                 p->confno = zi.confno;
1196         }
1197         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1198         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1199         return 0;
1200 }
1201
1202 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1203 {
1204         /* If they're listening to our channel, they're ours */ 
1205         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1206                 return 1;
1207         /* If they're a talker on our (allocated) conference, they're ours */
1208         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1209                 return 1;
1210         return 0;
1211 }
1212
1213 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1214 {
1215         ZT_CONFINFO zi;
1216         if (/* Can't delete if there's no zfd */
1217                 (c->zfd < 0) ||
1218                 /* Don't delete from the conference if it's not our conference */
1219                 !isourconf(p, c)
1220                 /* Don't delete if we don't think it's conferenced at all (implied) */
1221                 ) return 0;
1222         memset(&zi, 0, sizeof(zi));
1223         zi.chan = 0;
1224         zi.confno = 0;
1225         zi.confmode = 0;
1226         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1227                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1228                 return -1;
1229         }
1230         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1231         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1232         return 0;
1233 }
1234
1235 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1236 {
1237         int x;
1238         int useslavenative;
1239         struct zt_pvt *slave = NULL;
1240         /* Start out optimistic */
1241         useslavenative = 1;
1242         /* Update conference state in a stateless fashion */
1243         for (x=0;x<3;x++) {
1244                 /* Any three-way calling makes slave native mode *definitely* out
1245                    of the question */
1246                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1247                         useslavenative = 0;
1248         }
1249         /* If we don't have any 3-way calls, check to see if we have
1250            precisely one slave */
1251         if (useslavenative) {
1252                 for (x=0;x<MAX_SLAVES;x++) {
1253                         if (p->slaves[x]) {
1254                                 if (slave) {
1255                                         /* Whoops already have a slave!  No 
1256                                            slave native and stop right away */
1257                                         slave = NULL;
1258                                         useslavenative = 0;
1259                                         break;
1260                                 } else {
1261                                         /* We have one slave so far */
1262                                         slave = p->slaves[x];
1263                                 }
1264                         }
1265                 }
1266         }
1267         /* If no slave, slave native definitely out */
1268         if (!slave)
1269                 useslavenative = 0;
1270         else if (slave->law != p->law) {
1271                 useslavenative = 0;
1272                 slave = NULL;
1273         }
1274         if (out)
1275                 *out = slave;
1276         return useslavenative;
1277 }
1278
1279 static int reset_conf(struct zt_pvt *p)
1280 {
1281         ZT_CONFINFO zi;
1282         memset(&zi, 0, sizeof(zi));
1283         p->confno = -1;
1284         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1285         if (p->subs[SUB_REAL].zfd > -1) {
1286                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1287                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1288         }
1289         return 0;
1290 }
1291
1292 static int update_conf(struct zt_pvt *p)
1293 {
1294         int needconf = 0;
1295         int x;
1296         int useslavenative;
1297         struct zt_pvt *slave = NULL;
1298
1299         useslavenative = isslavenative(p, &slave);
1300         /* Start with the obvious, general stuff */
1301         for (x=0;x<3;x++) {
1302                 /* Look for three way calls */
1303                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1304                         conf_add(p, &p->subs[x], x, 0);
1305                         needconf++;
1306                 } else {
1307                         conf_del(p, &p->subs[x], x);
1308                 }
1309         }
1310         /* If we have a slave, add him to our conference now. or DAX
1311            if this is slave native */
1312         for (x=0;x<MAX_SLAVES;x++) {
1313                 if (p->slaves[x]) {
1314                         if (useslavenative)
1315                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1316                         else {
1317                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1318                                 needconf++;
1319                         }
1320                 }
1321         }
1322         /* If we're supposed to be in there, do so now */
1323         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1324                 if (useslavenative)
1325                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1326                 else {
1327                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1328                         needconf++;
1329                 }
1330         }
1331         /* If we have a master, add ourselves to his conference */
1332         if (p->master) {
1333                 if (isslavenative(p->master, NULL)) {
1334                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1335                 } else {
1336                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1337                 }
1338         }
1339         if (!needconf) {
1340                 /* Nobody is left (or should be left) in our conference.  
1341                    Kill it.  */
1342                 p->confno = -1;
1343         }
1344         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1345         return 0;
1346 }
1347
1348 static void zt_enable_ec(struct zt_pvt *p)
1349 {
1350         int x;
1351         int res;
1352         if (!p)
1353                 return;
1354         if (p->echocanon) {
1355                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1356                 return;
1357         }
1358         if (p->digital) {
1359                 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1360                 return;
1361         }
1362         if (p->echocancel) {
1363                 if (p->sig == SIG_PRI) {
1364                         x = 1;
1365                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1366                         if (res)
1367                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1368                 }
1369                 x = p->echocancel;
1370                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1371                 if (res) 
1372                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1373                 else {
1374                         p->echocanon = 1;
1375                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1376                 }
1377         } else
1378                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1379 }
1380
1381 static void zt_train_ec(struct zt_pvt *p)
1382 {
1383         int x;
1384         int res;
1385         if (p && p->echocancel && p->echotraining) {
1386                 x = p->echotraining;
1387                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1388                 if (res) 
1389                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1390                 else {
1391                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1392                 }
1393         } else
1394                 ast_log(LOG_DEBUG, "No echo training requested\n");
1395 }
1396
1397 static void zt_disable_ec(struct zt_pvt *p)
1398 {
1399         int x;
1400         int res;
1401         if (p->echocancel) {
1402                 x = 0;
1403                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1404                 if (res) 
1405                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1406                 else
1407                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1408         }
1409         p->echocanon = 0;
1410 }
1411
1412 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                                 fds[0].revents = 0;
2646                                 res = poll(fds, 1, -1);
2647                                 if (!res) {
2648                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2649                                         continue;
2650                                 }
2651                                   /* if got exception */
2652                                 if (fds[0].revents & POLLPRI) return -1;
2653                                 if (!(fds[0].revents & POLLOUT)) {
2654                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2655                                         continue;
2656                                 }
2657                                 res = write(fd, buf, size);
2658                                 if (res != size) {
2659                                         if (res == -1) return -1;
2660                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2661                                         break;
2662                                 }
2663                                 len -= size;
2664                                 buf += size;
2665                         }
2666                         p->didtdd = 1; /* set to have done it now */            
2667                 }
2668                 if (*cp == 2) { /* Mate mode */
2669                         if (p->tdd) tdd_free(p->tdd);
2670                         p->tdd = 0;
2671                         p->mate = 1;
2672                         break;
2673                         }               
2674                 if (!p->tdd) { /* if we dont have one yet */
2675                         p->tdd = tdd_new(); /* allocate one */
2676                 }               
2677                 break;
2678             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2679                 if (!p->dsp)
2680                         break;
2681                 if (!*cp)
2682                 {               
2683                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2684                         x = 0;
2685                 }
2686                 else
2687                 {               
2688                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2689                         x = 1;
2690                 }
2691                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2692                 break;
2693             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2694                 if (!*cp)
2695                 {               
2696                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2697                         x = 0;
2698                         zt_disable_ec(p);
2699                 }
2700                 else
2701                 {               
2702                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2703                         x = 1;
2704                 }
2705                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2706                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2707                 break;
2708         }
2709         errno = 0;
2710         return 0;
2711 }
2712
2713 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2714 {
2715         /* Unlink a specific slave or all slaves/masters from a given master */
2716         int x;
2717         int hasslaves;
2718         if (!master)
2719                 return;
2720         if (needlock) {
2721                 ast_mutex_lock(&master->lock);
2722                 if (slave) {
2723                         while(ast_mutex_trylock(&slave->lock)) {
2724                                 ast_mutex_unlock(&master->lock);
2725                                 usleep(1);
2726                                 ast_mutex_lock(&master->lock);
2727                         }
2728                 }
2729         }
2730         hasslaves = 0;
2731         for (x=0;x<MAX_SLAVES;x++) {
2732                 if (master->slaves[x]) {
2733                         if (!slave || (master->slaves[x] == slave)) {
2734                                 /* Take slave out of the conference */
2735                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2736                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2737                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2738                                 master->slaves[x]->master = NULL;
2739                                 master->slaves[x] = NULL;
2740                         } else
2741                                 hasslaves = 1;
2742                 }
2743                 if (!hasslaves)
2744                         master->inconference = 0;
2745         }
2746         if (!slave) {
2747                 if (master->master) {
2748                         /* Take master out of the conference */
2749                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2750                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2751                         hasslaves = 0;
2752                         for (x=0;x<MAX_SLAVES;x++) {
2753                                 if (master->master->slaves[x] == master)
2754                                         master->master->slaves[x] = NULL;
2755                                 else if (master->master->slaves[x])
2756                                         hasslaves = 1;
2757                         }
2758                         if (!hasslaves)
2759                                 master->master->inconference = 0;
2760                 }
2761                 master->master = NULL;
2762         }
2763         update_conf(master);
2764         if (needlock) {
2765                 if (slave)
2766                         ast_mutex_unlock(&slave->lock);
2767                 ast_mutex_unlock(&master->lock);
2768         }
2769 }
2770
2771 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2772         int x;
2773         if (!slave || !master) {
2774                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2775                 return;
2776         }
2777         for (x=0;x<MAX_SLAVES;x++) {
2778                 if (!master->slaves[x]) {
2779                         master->slaves[x] = slave;
2780                         break;
2781                 }
2782         }
2783         if (x >= MAX_SLAVES) {
2784                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2785                 master->slaves[MAX_SLAVES - 1] = slave;
2786         }
2787         if (slave->master) 
2788                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2789         slave->master = master;
2790         
2791         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2792 }
2793
2794 static void disable_dtmf_detect(struct zt_pvt *p)
2795 {
2796         int val;
2797
2798         p->ignoredtmf = 1;
2799
2800 #ifdef ZT_TONEDETECT
2801         val = 0;
2802         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
2803 #endif          
2804         
2805 }
2806
2807 static void enable_dtmf_detect(struct zt_pvt *p)
2808 {
2809         int val;
2810
2811         p->ignoredtmf = 0;
2812
2813 #ifdef ZT_TONEDETECT
2814         val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
2815         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
2816 #endif          
2817 }
2818
2819 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)
2820 {
2821         struct ast_channel *who;
2822         struct zt_pvt *p0, *p1, *op0, *op1;
2823         struct zt_pvt *master = NULL, *slave = NULL;
2824         struct ast_frame *f;
2825         int to;
2826         int inconf = 0;
2827         int nothingok = 1;
2828         int ofd0, ofd1;
2829         int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
2830         int os0 = -1, os1 = -1;
2831         struct ast_channel *oc0, *oc1;
2832         enum ast_bridge_result res;
2833
2834 #ifdef PRI_2BCT
2835         int triedtopribridge = 0;
2836         q931_call *q931c0 = NULL, *q931c1 = NULL;
2837 #endif
2838
2839         /* For now, don't attempt to native bridge if either channel needs DTMF detection.
2840            There is code below to handle it properly until DTMF is actually seen,
2841            but due to currently unresolved issues it's ignored...
2842         */
2843
2844         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2845                 return AST_BRIDGE_FAILED_NOWARN;
2846
2847         ast_mutex_lock(&c0->lock);
2848         ast_mutex_lock(&c1->lock);
2849
2850         p0 = c0->tech_pvt;
2851         p1 = c1->tech_pvt;
2852         /* cant do pseudo-channels here */
2853         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2854                 ast_mutex_unlock(&c0->lock);
2855                 ast_mutex_unlock(&c1->lock);
2856                 return AST_BRIDGE_FAILED_NOWARN;
2857         }
2858
2859         oi0 = zt_get_index(c0, p0, 0);
2860         oi1 = zt_get_index(c1, p1, 0);
2861         if ((oi0 < 0) || (oi1 < 0)) {
2862                 ast_mutex_unlock(&c0->lock);
2863                 ast_mutex_unlock(&c1->lock);
2864                 return AST_BRIDGE_FAILED;
2865         }
2866
2867         op0 = p0 = c0->tech_pvt;
2868         op1 = p1 = c1->tech_pvt;
2869         ofd0 = c0->fds[0];
2870         ofd1 = c1->fds[0];
2871         oc0 = p0->owner;
2872         oc1 = p1->owner;
2873
2874         ast_mutex_lock(&p0->lock);
2875         if (ast_mutex_trylock(&p1->lock)) {
2876                 /* Don't block, due to potential for deadlock */
2877                 ast_mutex_unlock(&p0->lock);
2878                 ast_mutex_unlock(&c0->lock);
2879                 ast_mutex_unlock(&c1->lock);
2880                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2881                 return AST_BRIDGE_RETRY;
2882         }
2883
2884         if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
2885                 if (p0->owner && p1->owner) {
2886                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2887                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2888                                 master = p0;
2889                                 slave = p1;
2890                                 inconf = 1;
2891                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2892                                 master = p1;
2893                                 slave = p0;
2894                                 inconf = 1;
2895                         } else {
2896                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2897                                 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n",
2898                                         p0->channel,
2899                                         oi0, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
2900                                         p0->subs[SUB_REAL].inthreeway, p0->channel,
2901                                         oi0, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0,
2902                                         p1->subs[SUB_REAL].inthreeway);
2903                         }
2904                         nothingok = 0;
2905                 }
2906         } else if ((oi0 == SUB_REAL) && (oi1 == SUB_THREEWAY)) {
2907                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2908                         master = p1;
2909                         slave = p0;
2910                         nothingok = 0;
2911                 }
2912         } else if ((oi0 == SUB_THREEWAY) && (oi1 == SUB_REAL)) {
2913                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2914                         master = p0;
2915                         slave = p1;
2916                         nothingok = 0;
2917                 }
2918         } else if ((oi0 == SUB_REAL) && (oi1 == SUB_CALLWAIT)) {
2919                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2920                    don't put us in anything */
2921                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2922                         master = p1;
2923                         slave = p0;
2924                         nothingok = 0;
2925                 }
2926         } else if ((oi0 == SUB_CALLWAIT) && (oi1 == SUB_REAL)) {
2927                 /* Same as previous */
2928                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2929                         master = p0;
2930                         slave = p1;
2931                         nothingok = 0;
2932                 }
2933         }
2934         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2935                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2936         if (master && slave) {
2937                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2938                    in an active threeway call with a channel that is ringing, we should
2939                    indicate ringing. */
2940                 if ((oi1 == SUB_THREEWAY) && 
2941                     p1->subs[SUB_THREEWAY].inthreeway && 
2942                     p1->subs[SUB_REAL].owner && 
2943                     p1->subs[SUB_REAL].inthreeway && 
2944                     (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2945                         ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2946                         tone_zone_play_tone(p0->subs[oi0].zfd, ZT_TONE_RINGTONE);
2947                         os1 = p1->subs[SUB_REAL].owner->_state;
2948                 } else {
2949                         ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p0->channel, oi0, p1->channel, oi1);
2950                         tone_zone_play_tone(p0->subs[oi0].zfd, -1);
2951                 }
2952                 if ((oi0 == SUB_THREEWAY) && 
2953                     p0->subs[SUB_THREEWAY].inthreeway && 
2954                     p0->subs[SUB_REAL].owner && 
2955                     p0->subs[SUB_REAL].inthreeway && 
2956                     (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2957                         ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2958                         tone_zone_play_tone(p1->subs[oi1].zfd, ZT_TONE_RINGTONE);
2959                         os0 = p0->subs[SUB_REAL].owner->_state;
2960                 } else {
2961                         ast_log(LOG_DEBUG, "Stopping tones on %d/%d talking to %d/%d\n", p1->channel, oi1, p0->channel, oi0);
2962                         tone_zone_play_tone(p1->subs[oi0].zfd, -1);
2963                 }
2964                 if ((oi0 == SUB_REAL) && (oi1 == SUB_REAL)) {
2965                         if (!p0->echocanbridged || !p1->echocanbridged) {
2966                                 /* Disable echo cancellation if appropriate */
2967                                 zt_disable_ec(p0);
2968                                 zt_disable_ec(p1);
2969                         }
2970                 }
2971                 zt_link(slave, master);
2972                 master->inconference = inconf;
2973         } else if (!nothingok)
2974                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi0], p1->channel, subnames[oi1]);
2975
2976         update_conf(p0);
2977         update_conf(p1);
2978         t0 = p0->subs[SUB_REAL].inthreeway;
2979         t1 = p1->subs[SUB_REAL].inthreeway;
2980
2981         ast_mutex_unlock(&p0->lock);
2982         ast_mutex_unlock(&p1->lock);
2983
2984         ast_mutex_unlock(&c0->lock);
2985         ast_mutex_unlock(&c1->lock);
2986
2987         /* Native bridge failed */
2988         if ((!master || !slave) && !nothingok) {
2989                 zt_enable_ec(p0);
2990                 zt_enable_ec(p1);
2991                 return AST_BRIDGE_FAILED;
2992         }
2993         
2994         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0))
2995                 disable_dtmf_detect(op0);
2996
2997         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1))
2998                 disable_dtmf_detect(op1);
2999
3000         for (;;) {
3001                 struct ast_channel *c0_priority[2] = {c0, c1};
3002                 struct ast_channel *c1_priority[2] = {c1, c0};
3003                 int priority = 0;
3004
3005                 /* Here's our main loop...  Start by locking things, looking for private parts, 
3006                    and then balking if anything is wrong */
3007                 ast_mutex_lock(&c0->lock);
3008                 ast_mutex_lock(&c1->lock);
3009                 p0 = c0->tech_pvt;
3010                 p1 = c1->tech_pvt;
3011
3012                 if (op0 == p0)
3013                         i0 = zt_get_index(c0, p0, 1);
3014                 if (op1 == p1)
3015                         i1 = zt_get_index(c1, p1, 1);
3016                 ast_mutex_unlock(&c0->lock);
3017                 ast_mutex_unlock(&c1->lock);
3018
3019                 if ((op0 != p0) ||
3020                     (op1 != p1) || 
3021                     (ofd0 != c0->fds[0]) || 
3022                     (ofd1 != c1->fds[0]) ||
3023                     (p0->subs[SUB_REAL].owner && (os0 > -1) && (os0 != p0->subs[SUB_REAL].owner->_state)) || 
3024                     (p1->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p1->subs[SUB_REAL].owner->_state)) || 
3025                     (oc0 != p0->owner) || 
3026                     (oc1 != p1->owner) ||
3027                     (t0 != p0->subs[SUB_REAL].inthreeway) ||
3028                     (t1 != p1->subs[SUB_REAL].inthreeway) ||
3029                     (oi0 != i0) ||
3030                     (oi1 != i0)) {
3031                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
3032                                 op0->channel, oi0, op1->channel, oi1);
3033                         res = AST_BRIDGE_RETRY;
3034                         goto return_from_bridge;
3035                 }
3036
3037 #ifdef PRI_2BCT
3038                 q931c0 = p0->call;
3039                 q931c1 = p1->call;
3040                 if (p0->transfer && p1->transfer 
3041                     && q931c0 && q931c1 
3042                     && !triedtopribridge) {
3043                         pri_channel_bridge(q931c0, q931c1);
3044                         triedtopribridge = 1;
3045                 }
3046 #endif
3047
3048                 to = -1;
3049                 who = ast_waitfor_n(priority ? c0_priority : c1_priority, 2, &to);
3050                 if (!who) {
3051                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
3052                         continue;
3053                 }
3054                 f = ast_read(who);
3055                 if (!f || (f->frametype == AST_FRAME_CONTROL)) {
3056                         *fo = f;
3057                         *rc = who;
3058                         res = AST_BRIDGE_COMPLETE;
3059                         goto return_from_bridge;
3060                 }
3061                 if (f->frametype == AST_FRAME_DTMF) {
3062                         if ((who == c0) && p0->pulsedial) {
3063                                 ast_write(c1, f);
3064                         } else if (p1->pulsedial) {
3065                                 ast_write(c0, f);
3066                         } else {
3067                                 *fo = f;
3068                                 *rc = who;
3069                                 res = AST_BRIDGE_COMPLETE;
3070                                 goto return_from_bridge;
3071                         }
3072                 }
3073                 ast_frfree(f);
3074                 
3075                 /* Swap who gets priority */
3076                 priority = !priority;
3077         }
3078
3079 return_from_bridge:
3080         if (op0 == p0)
3081                 zt_enable_ec(p0);
3082
3083         if (op1 == p1)
3084                 zt_enable_ec(p1);
3085
3086         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_0))
3087                 enable_dtmf_detect(op0);
3088
3089         if (!(flags & AST_BRIDGE_DTMF_CHANNEL_1))
3090                 enable_dtmf_detect(op1);
3091
3092         zt_unlink(slave, master, 1);
3093
3094         return res;
3095 }
3096
3097 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3098 {
3099         struct zt_pvt *p = newchan->tech_pvt;
3100         int x;
3101         ast_mutex_lock(&p->lock);
3102         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3103         if (p->owner == oldchan) {
3104                 p->owner = newchan;
3105         }
3106         for (x=0;x<3;x++)
3107                 if (p->subs[x].owner == oldchan) {
3108                         if (!x)
3109                                 zt_unlink(NULL, p, 0);
3110                         p->subs[x].owner = newchan;
3111                 }
3112         if (newchan->_state == AST_STATE_RINGING) 
3113                 zt_indicate(newchan, AST_CONTROL_RINGING);
3114         update_conf(p);
3115         ast_mutex_unlock(&p->lock);
3116         return 0;
3117 }
3118
3119 static int zt_ring_phone(struct zt_pvt *p)
3120 {
3121         int x;
3122         int res;
3123         /* Make sure our transmit state is on hook */
3124         x = 0;
3125         x = ZT_ONHOOK;
3126         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3127         do {
3128                 x = ZT_RING;
3129                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3130 #if 0
3131                 printf("Res: %d, error: %s\n", res, strerror(errno));
3132 #endif                                          
3133                 if (res) {
3134                         switch(errno) {
3135                         case EBUSY:
3136                         case EINTR:
3137                                 /* Wait just in case */
3138                                 usleep(10000);
3139                                 continue;
3140                         case EINPROGRESS:
3141                                 res = 0;
3142                                 break;
3143                         default:
3144                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3145                                 res = 0;
3146                         }
3147                 }
3148         } while (res);
3149         return res;
3150 }
3151
3152 static void *ss_thread(void *data);
3153
3154 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3155
3156 static int attempt_transfer(struct zt_pvt *p)
3157 {
3158         /* In order to transfer, we need at least one of the channels to
3159            actually be in a call bridge.  We can't conference two applications
3160            together (but then, why would we want to?) */
3161         if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3162                 /* The three-way person we're about to transfer to could still be in MOH, so
3163                    stop if now if appropriate */
3164                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3165                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3166                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3167                         ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3168                 }
3169                 if (p->subs[SUB_REAL].owner->cdr) {
3170                         /* Move CDR from second channel to current one */
3171                         p->subs[SUB_THREEWAY].owner->cdr =
3172                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3173                         p->subs[SUB_REAL].owner->cdr = NULL;
3174                 }
3175                 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3176                         /* Move CDR from second channel's bridge to current one */
3177                         p->subs[SUB_THREEWAY].owner->cdr =
3178                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3179                         ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3180                 }
3181                  if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3182                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3183                                         ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3184                         return -1;
3185                 }
3186                 /* Orphan the channel after releasing the lock */
3187                 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3188                 unalloc_sub(p, SUB_THREEWAY);
3189         } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3190                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
3191                         ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3192                 }
3193                 ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3194                 if (p->subs[SUB_THREEWAY].owner->cdr) {
3195                         /* Move CDR from second channel to current one */
3196                         p->subs[SUB_REAL].owner->cdr = 
3197                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3198                         p->subs[SUB_THREEWAY].owner->cdr = NULL;
3199                 }
3200                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3201                         /* Move CDR from second channel's bridge to current one */
3202                         p->subs[SUB_REAL].owner->cdr = 
3203                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
3204                         ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
3205                 }
3206                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
3207                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3208                                         ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
3209                         return -1;
3210                 }
3211                 /* Three-way is now the REAL */
3212                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3213                 ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
3214                 unalloc_sub(p, SUB_THREEWAY);
3215                 /* Tell the caller not to hangup */
3216                 return 1;
3217         } else {
3218                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3219                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
3220                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3221                 return -1;
3222         }
3223         return 0;
3224 }
3225
3226 #ifdef ZAPATA_R2
3227 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
3228 {
3229         struct ast_frame *f;
3230         f = &p->subs[index].f;
3231         if (!p->r2) {
3232                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
3233                 return NULL;
3234         }
3235         switch(e->e) {
3236         case MFCR2_EVENT_BLOCKED:
3237                 if (option_verbose > 2)
3238                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
3239                 break;
3240         case MFCR2_EVENT_UNBLOCKED:
3241                 if (option_verbose > 2)
3242                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
3243                 break;
3244         case MFCR2_EVENT_CONFIG_ERR:
3245                 if (option_verbose > 2)
3246                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
3247                 break;
3248         case MFCR2_EVENT_RING:
3249                 if (option_verbose > 2)
3250                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
3251                 break;
3252         case MFCR2_EVENT_HANGUP:
3253                 if (option_verbose > 2)
3254                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
3255                 break;
3256         case MFCR2_EVENT_RINGING:
3257                 if (option_verbose > 2)
3258                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
3259                 break;
3260         case MFCR2_EVENT_ANSWER:
3261                 if (option_verbose > 2)
3262                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
3263                 break;
3264         case MFCR2_EVENT_HANGUP_ACK:
3265                 if (option_verbose > 2)
3266                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
3267                 break;
3268         case MFCR2_EVENT_IDLE:
3269                 if (option_verbose > 2)
3270                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
3271                 break;
3272         default:
3273                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
3274                 break;
3275         }
3276         return f;
3277 }
3278
3279 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
3280 {
3281         int x;
3282         int res;
3283         mfcr2_event_t *e;
3284         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
3285         if (res) {
3286                 ast_log(LOG_WARNING, "Unable to check received bits\n");
3287                 return NULL;
3288         }
3289         if (!p->r2) {
3290                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
3291                 return NULL;
3292         }
3293         e = mfcr2_cas_signaling_event(p->r2, x);
3294         return e;
3295 }
3296 #endif
3297
3298 static int check_for_conference(struct zt_pvt *p)
3299 {
3300         ZT_CONFINFO ci;
3301         /* Fine if we already have a master, etc */
3302         if (p->master || (p->confno > -1))
3303                 return 0;
3304         memset(&ci, 0, sizeof(ci));
3305         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
3306                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
3307                 return 0;
3308         }
3309         /* If we have no master and don't have a confno, then 
3310            if we're in a conference, it's probably a MeetMe room or
3311            some such, so don't let us 3-way out! */
3312         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
3313                 if (option_verbose > 2) 
3314                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
3315                 return 1;
3316         }
3317         return 0;
3318 }
3319
3320 static int get_alarms(struct zt_pvt *p)
3321 {
3322         int res;
3323         ZT_SPANINFO zi;
3324         memset(&zi, 0, sizeof(zi));
3325         zi.spanno = p->span;
3326         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
3327         if (res < 0) {
3328                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
3329                 return 0;
3330         }
3331         return zi.alarms;
3332 }
3333                         
3334 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
3335 {
3336         int res,x;
3337         int index;
3338         char *c;
3339         struct zt_pvt *p = ast->tech_pvt;
3340         pthread_t threadid;
3341         pthread_attr_t attr;
3342         struct ast_channel *chan;
3343
3344         pthread_attr_init(&attr);
3345         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3346
3347         index = zt_get_index(ast, p, 0);
3348         p->subs[index].f.frametype = AST_FRAME_NULL;
3349         p->subs[index].f.datalen = 0;
3350         p->subs[index].f.samples = 0;
3351         p->subs[index].f.mallocd = 0;
3352         p->subs[index].f.offset = 0;
3353         p->subs[index].f.src = "zt_handle_event";
3354         p->subs[index].f.data = NULL;
3355         if (index < 0)
3356                 return &p->subs[index].f;
3357         if (p->fake_event) {
3358                 res = p->fake_event;
3359                 p->fake_event = 0;
3360         } else
3361                 res = zt_get_event(p->subs[index].zfd);
3362
3363         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
3364
3365         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
3366                 if (res & ZT_EVENT_PULSEDIGIT)
3367                         p->pulsedial = 1;
3368                 else
3369                         p->pulsedial = 0;
3370                 ast_log(LOG_DEBUG, "Detected %sdigit '%c'\n", p->pulsedial ? "pulse ": "", res & 0xff);
3371 #ifdef ZAPATA_PRI
3372                 if ((p->proceeding < 2) && p->sig == SIG_PRI && p->pri && p->pri->overlapdial) {
3373                         p->subs[index].f.frametype = AST_FRAME_NULL;
3374                         p->subs[index].f.subclass = 0;
3375                 } else {
3376 #endif
3377                         p->subs[index].f.frametype = AST_FRAME_DTMF;
3378                         p->subs[index].f.subclass = res & 0xff;
3379 #ifdef ZAPATA_PRI
3380                 }
3381 #endif
3382                 /* Unmute conference, return the captured digit */
3383                 zt_confmute(p, 0);
3384                 return &p->subs[index].f;
3385         }
3386
3387         if (res & ZT_EVENT_DTMFDOWN) {
3388                 ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
3389                 p->subs[index].f.frametype = AST_FRAME_NULL;
3390                 p->subs[index].f.subclass = 0;
3391                 zt_confmute(p, 1);
3392                 /* Mute conference, return null frame */
3393                 return &p->subs[index].f;
3394         }
3395
3396         switch(res) {
3397                 case ZT_EVENT_BITSCHANGED:
3398                         if (p->sig == SIG_R2) {
3399 #ifdef ZAPATA_R2
3400                                 struct ast_frame  *f = &p->subs[index].f;
3401                                 mfcr2_event_t *e;
3402                                 e = r2_get_event_bits(p);
3403                                 if (e)
3404                                         f = handle_r2_event(p, e, index);
3405                                 return f;
3406 #else                           
3407                                 break;
3408 #endif
3409                         }
3410                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
3411                 case ZT_EVENT_PULSE_START:
3412                         /* Stop tone if there's a pulse start and the PBX isn't started */
3413                         if (!ast->pbx)
3414                                 tone_zone_play_tone(p->subs[index].zfd, -1);
3415                         break;  
3416                 case ZT_EVENT_DIALCOMPLETE:
3417                         if (p->inalarm) break;
3418                         if (p->radio) break;
3419                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
3420                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
3421                                 return NULL;
3422                         }
3423                         if (!x) { /* if not still dialing in driver */
3424                                 zt_enable_ec(p);
3425                                 if (p->echobreak) {
3426                                         zt_train_ec(p);
3427                                         ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
3428                                         p->dop.op = ZT_DIAL_OP_REPLACE;
3429                                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3430                                         p->echobreak = 0;
3431