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