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