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