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