Add separated dialplan support (bug #2043)
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Zaptel Pseudo TDM interface 
5  * 
6  * Copyright (C) 2003 Digium
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <string.h>
16 #include <asterisk/lock.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/channel_pvt.h>
19 #include <asterisk/config.h>
20 #include <asterisk/logger.h>
21 #include <asterisk/module.h>
22 #include <asterisk/pbx.h>
23 #include <asterisk/options.h>
24 #include <asterisk/file.h>
25 #include <asterisk/ulaw.h>
26 #include <asterisk/alaw.h>
27 #include <asterisk/callerid.h>
28 #include <asterisk/adsi.h>
29 #include <asterisk/cli.h>
30 #include <asterisk/cdr.h>
31 #include <asterisk/parking.h>
32 #include <asterisk/musiconhold.h>
33 #include <asterisk/say.h>
34 #include <asterisk/tdd.h>
35 #include <asterisk/app.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/astdb.h>
38 #include <asterisk/manager.h>
39 #include <asterisk/causes.h>
40 #include <asterisk/term.h>
41 #include <asterisk/utils.h>
42 #include <sys/signal.h>
43 #include <errno.h>
44 #include <stdlib.h>
45 #include <stdint.h>
46 #include <unistd.h>
47 #include <sys/ioctl.h>
48 #ifdef __linux__
49 #include <linux/zaptel.h>
50 #else
51 #include <zaptel.h>
52 #endif /* __linux__ */
53 #include <math.h>
54 #include <tonezone.h>
55 #include <ctype.h>
56 #ifdef ZAPATA_PRI
57 #include <libpri.h>
58 #ifndef PRI_NSF_NONE
59 #error "You need newer libpri"
60 #endif
61 #endif
62 #ifdef ZAPATA_R2
63 #include <libmfcr2.h>
64 #endif
65
66 #include "../asterisk.h"
67
68 #ifndef ZT_SIG_EM_E1
69 #error "Your zaptel is too old.  please cvs update"
70 #endif
71
72 /*
73  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
74  * the user hangs up to reset the state machine so ring works properly.
75  * This is used to be able to support kewlstart by putting the zhone in
76  * groundstart mode since their forward disconnect supervision is entirely
77  * broken even though their documentation says it isn't and their support
78  * is entirely unwilling to provide any assistance with their channel banks
79  * even though their web site says they support their products for life.
80  */
81
82 /* #define ZHONE_HACK */
83
84 /* Typically, how many rings before we should send Caller*ID */
85 #define DEFAULT_CIDRINGS 1
86
87 #define CHANNEL_PSEUDO -12
88
89 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
90
91 static char *desc = "Zapata Telephony"
92 #ifdef ZAPATA_PRI
93                " w/PRI"
94 #endif
95 #ifdef ZAPATA_R2
96                " w/R2"
97 #endif
98 ;
99
100 static char *tdesc = "Zapata Telephony Driver"
101 #ifdef ZAPATA_PRI
102                " w/PRI"
103 #endif
104 #ifdef ZAPATA_R2
105                " w/R2"
106 #endif
107 ;
108
109 static char *type = "Zap";
110 static char *typecompat = "Tor";        /* Retain compatibility with chan_tor */
111 static char *config = "zapata.conf";
112
113 #define SIG_EM          ZT_SIG_EM
114 #define SIG_EMWINK      (0x100000 | ZT_SIG_EM)
115 #define SIG_FEATD       (0x200000 | ZT_SIG_EM)
116 #define SIG_FEATDMF     (0x400000 | ZT_SIG_EM)
117 #define SIG_FEATB       (0x800000 | ZT_SIG_EM)
118 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
119 #define SIG_FXSLS       ZT_SIG_FXSLS
120 #define SIG_FXSGS       ZT_SIG_FXSGS
121 #define SIG_FXSKS       ZT_SIG_FXSKS
122 #define SIG_FXOLS       ZT_SIG_FXOLS
123 #define SIG_FXOGS       ZT_SIG_FXOGS
124 #define SIG_FXOKS       ZT_SIG_FXOKS
125 #define SIG_PRI         ZT_SIG_CLEAR
126 #define SIG_R2          ZT_SIG_CAS
127 #define SIG_SF          ZT_SIG_SF
128 #define SIG_SFWINK      (0x100000 | ZT_SIG_SF)
129 #define SIG_SF_FEATD    (0x200000 | ZT_SIG_SF)
130 #define SIG_SF_FEATDMF  (0x400000 | ZT_SIG_SF)
131 #define SIG_SF_FEATB    (0x800000 | ZT_SIG_SF)
132 #define SIG_EM_E1       ZT_SIG_EM_E1
133 #define SIG_GR303FXOKS   (0x100000 | ZT_SIG_FXOKS)
134 #define SIG_GR303FXSKS   (0x200000 | ZT_SIG_FXSKS)
135
136 #define NUM_SPANS       32
137 #define NUM_DCHANS      4               /* No more than 4 d-channels */
138 #define MAX_CHANNELS    672     /* No more than a DS3 per trunk group */
139 #define RESET_INTERVAL  3600    /* How often (in seconds) to reset unused channels */
140
141 #define CHAN_PSEUDO     -2
142
143 #define DCHAN_PROVISIONED (1 << 0)
144 #define DCHAN_NOTINALARM  (1 << 1)
145 #define DCHAN_UP          (1 << 2)
146
147 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
148
149 static char context[AST_MAX_EXTENSION] = "default";
150 static char callerid[256] = "";
151
152 static char language[MAX_LANGUAGE] = "";
153 static char musicclass[MAX_LANGUAGE] = "";
154 static char progzone[10]= "";
155
156 static int usedistinctiveringdetection = 0;
157
158 static int use_callerid = 1;
159 static int zaptrcallerid = 0;
160 static int cur_signalling = -1;
161
162 static unsigned int cur_group = 0;
163 static unsigned int cur_callergroup = 0;
164 static unsigned int cur_pickupgroup = 0;
165 static int relaxdtmf = 0;
166
167 static int immediate = 0;
168
169 static int stripmsd = 0;
170
171 static int callwaiting = 0;
172
173 static int callwaitingcallerid = 0;
174
175 static int hidecallerid = 0;
176
177 static int restrictcid = 0;
178
179 static int use_callingpres = 0;
180
181 static int callreturn = 0;
182
183 static int threewaycalling = 0;
184
185 static int transfer = 0;
186
187 static int cancallforward = 0;
188
189 static float rxgain = 0.0;
190
191 static float txgain = 0.0;
192
193 static int tonezone = -1;
194
195 static int echocancel;
196
197 static int echotraining;
198
199 static int echocanbridged = 0;
200
201 static int busydetect = 0;
202
203 static int busycount = 3;
204
205 static int callprogress = 0;
206
207 static char accountcode[20] = "";
208
209 static char mailbox[AST_MAX_EXTENSION];
210
211 static int amaflags = 0;
212
213 static int adsi = 0;
214
215 static int numbufs = 4;
216
217 static int cur_prewink = -1;
218 static int cur_preflash = -1;
219 static int cur_wink = -1;
220 static int cur_flash = -1;
221 static int cur_start = -1;
222 static int cur_rxwink = -1;
223 static int cur_rxflash = -1;
224 static int cur_debounce = -1;
225
226 #ifdef ZAPATA_PRI
227 static int minunused = 2;
228 static int minidle = 0;
229 static char idleext[AST_MAX_EXTENSION];
230 static char idledial[AST_MAX_EXTENSION];
231 static int overlapdial = 0;
232 static struct ast_channel inuse = { "GR-303InUse" };
233 #endif
234
235 /* Wait up to 16 seconds for first digit (FXO logic) */
236 static int firstdigittimeout = 16000;
237
238 /* How long to wait for following digits (FXO logic) */
239 static int gendigittimeout = 8000;
240
241 /* How long to wait for an extra digit, if there is an ambiguous match */
242 static int matchdigittimeout = 3000;
243
244 static int usecnt =0;
245 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
246
247 /* Protect the interface list (of zt_pvt's) */
248 AST_MUTEX_DEFINE_STATIC(iflock);
249
250 static int ifcount = 0;
251
252 /* Protect the monitoring thread, so only one process can kill or start it, and not
253    when it's doing something critical. */
254 AST_MUTEX_DEFINE_STATIC(monlock);
255
256 /* This is the thread for the monitor which checks for input on the channels
257    which are not currently in use.  */
258 static pthread_t monitor_thread = AST_PTHREADT_NULL;
259
260 static int restart_monitor(void);
261
262 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
263
264 static int zt_sendtext(struct ast_channel *c, char *text);
265
266 static inline int zt_get_event(int fd)
267 {
268         /* Avoid the silly zt_getevent which ignores a bunch of events */
269         int j;
270         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
271         return j;
272 }
273
274 static inline int zt_wait_event(int fd)
275 {
276         /* Avoid the silly zt_waitevent which ignores a bunch of events */
277         int i,j=0;
278         i = ZT_IOMUX_SIGEVENT;
279         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
280         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
281         return j;
282 }
283
284 /* Chunk size to read -- we use 20ms chunks to make things happy.  */   
285 #define READ_SIZE 160
286
287 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
288 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
289
290 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
291 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
292 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /* 500 ms */
293 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /* 2000 ms */
294 #define RINGT                                           ( (8000 * 8) / READ_SIZE)
295
296 struct zt_pvt;
297
298
299 #ifdef ZAPATA_R2
300 static int r2prot = -1;
301 #endif
302
303
304 #ifdef ZAPATA_PRI
305
306 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8))
307 #define PRI_CHANNEL(p) ((p) & 0xff)
308 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
309
310 struct zt_pri {
311         pthread_t master;                       /* Thread of master */
312         ast_mutex_t lock;               /* Mutex */
313         char idleext[AST_MAX_EXTENSION];                /* Where to idle extra calls */
314         char idlecontext[AST_MAX_EXTENSION];            /* What context to use for idle */
315         char idledial[AST_MAX_EXTENSION];               /* What to dial before dumping */
316         int minunused;                          /* Min # of channels to keep empty */
317         int minidle;                            /* Min # of "idling" calls to keep active */
318         int nodetype;                           /* Node type */
319         int switchtype;                         /* Type of switch to emulate */
320         int nsf;                        /* Network-Specific Facilities */
321         int dialplan;                   /* Dialing plan */
322         int 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 update_conf(struct zt_pvt *p)
1132 {
1133         int needconf = 0;
1134         int x;
1135         int useslavenative;
1136         struct zt_pvt *slave = NULL;
1137
1138         useslavenative = isslavenative(p, &slave);
1139         /* Start with the obvious, general stuff */
1140         for (x=0;x<3;x++) {
1141                 /* Look for three way calls */
1142                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1143                         conf_add(p, &p->subs[x], x, 0);
1144                         needconf++;
1145                 } else {
1146                         conf_del(p, &p->subs[x], x);
1147                 }
1148         }
1149         /* If we have a slave, add him to our conference now. or DAX
1150            if this is slave native */
1151         for (x=0;x<MAX_SLAVES;x++) {
1152                 if (p->slaves[x]) {
1153                         if (useslavenative)
1154                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1155                         else {
1156                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1157                                 needconf++;
1158                         }
1159                 }
1160         }
1161         /* If we're supposed to be in there, do so now */
1162         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1163                 if (useslavenative)
1164                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1165                 else {
1166                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1167                         needconf++;
1168                 }
1169         }
1170         /* If we have a master, add ourselves to his conference */
1171         if (p->master) {
1172                 if (isslavenative(p->master, NULL)) {
1173                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1174                 } else {
1175                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1176                 }
1177         }
1178         if (!needconf) {
1179                 /* Nobody is left (or should be left) in our conference.  
1180                    Kill it.  */
1181                 p->confno = -1;
1182         }
1183         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1184         return 0;
1185 }
1186
1187 static void zt_enable_ec(struct zt_pvt *p)
1188 {
1189         int x;
1190         int res;
1191         if (p->echocanon) {
1192                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1193                 return;
1194         }
1195         if (p && p->echocancel) {
1196                 if (p->sig == SIG_PRI) {
1197                         x = 1;
1198                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1199                         if (res)
1200                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1201                 }
1202                 x = p->echocancel;
1203                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1204                 if (res) 
1205                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1206                 else {
1207                         p->echocanon = 1;
1208                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1209                 }
1210         } else
1211                 ast_log(LOG_DEBUG, "No echocancellation requested\n");
1212 }
1213
1214 static void zt_train_ec(struct zt_pvt *p)
1215 {
1216         int x;
1217         int res;
1218         if (p && p->echocancel && p->echotraining) {
1219                 x = p->echotraining;
1220                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1221                 if (res) 
1222                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1223                 else {
1224                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1225                 }
1226         } else
1227                 ast_log(LOG_DEBUG, "No echo training requested\n");
1228 }
1229
1230 static void zt_disable_ec(struct zt_pvt *p)
1231 {
1232         int x;
1233         int res;
1234         if (p->echocancel) {
1235                 x = 0;
1236                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1237                 if (res) 
1238                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1239                 else
1240                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1241         }
1242         p->echocanon = 0;
1243 }
1244
1245 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1246 {
1247         struct  zt_gains g;
1248         float ltxgain;
1249         float lrxgain;
1250         int j,k;
1251         g.chan = chan;
1252         if ((rxgain != 0.0)  || (txgain != 0.0)) {
1253                 /* caluculate linear value of tx gain */
1254                 ltxgain = pow(10.0,txgain / 20.0);
1255                 /* caluculate linear value of rx gain */
1256                 lrxgain = pow(10.0,rxgain / 20.0);
1257                 if (law == ZT_LAW_ALAW) {
1258                         for (j=0;j<256;j++) {
1259                                 k = (int)(((float)AST_ALAW(j)) * lrxgain);
1260                                 if (k > 32767) k = 32767;
1261                                 if (k < -32767) k = -32767;
1262                                 g.rxgain[j] = AST_LIN2A(k);
1263                                 k = (int)(((float)AST_ALAW(j)) * ltxgain);
1264                                 if (k > 32767) k = 32767;
1265                                 if (k < -32767) k = -32767;
1266                                 g.txgain[j] = AST_LIN2A(k);
1267                         }
1268                 } else {
1269                         for (j=0;j<256;j++) {
1270                                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
1271                                 if (k > 32767) k = 32767;
1272                                 if (k < -32767) k = -32767;
1273                                 g.rxgain[j] = AST_LIN2MU(k);
1274                                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
1275                                 if (k > 32767) k = 32767;
1276                                 if (k < -32767) k = -32767;
1277                                 g.txgain[j] = AST_LIN2MU(k);
1278                         }
1279                 }
1280         } else {
1281                 for (j=0;j<256;j++) {
1282                         g.rxgain[j] = j;
1283                         g.txgain[j] = j;
1284                 }
1285         }
1286                 
1287           /* set 'em */
1288         return(ioctl(fd,ZT_SETGAINS,&g));
1289 }
1290
1291 static inline int zt_set_hook(int fd, int hs)
1292 {
1293         int x, res;
1294         x = hs;
1295         res = ioctl(fd, ZT_HOOK, &x);
1296         if (res < 0) 
1297         {
1298                 if (errno == EINPROGRESS) return 0;
1299                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1300         }
1301         return res;
1302 }
1303
1304 static inline int zt_confmute(struct zt_pvt *p, int muted)
1305 {
1306         int x, y, res;
1307         x = muted;
1308         if (p->sig == SIG_PRI) {
1309                 y = 1;
1310                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1311                 if (res)
1312                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1313         }
1314         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1315         if (res < 0) 
1316                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1317         return res;
1318 }
1319
1320 static int save_conference(struct zt_pvt *p)
1321 {
1322         struct zt_confinfo c;
1323         int res;
1324         if (p->saveconf.confmode) {
1325                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1326                 return -1;
1327         }
1328         p->saveconf.chan = 0;
1329         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1330         if (res) {
1331                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1332                 p->saveconf.confmode = 0;
1333                 return -1;
1334         }
1335         c.chan = 0;
1336         c.confno = 0;
1337         c.confmode = ZT_CONF_NORMAL;
1338         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1339         if (res) {
1340                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1341                 return -1;
1342         }
1343         if (option_debug)
1344                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1345         return 0;
1346 }
1347
1348 static int restore_conference(struct zt_pvt *p)
1349 {
1350         int res;
1351         if (p->saveconf.confmode) {
1352                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1353                 p->saveconf.confmode = 0;
1354                 if (res) {
1355                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1356                         return -1;
1357                 }
1358         }
1359         if (option_debug)
1360                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1361         return 0;
1362 }
1363
1364 static int send_callerid(struct zt_pvt *p);
1365
1366 int send_cwcidspill(struct zt_pvt *p)
1367 {
1368         p->callwaitcas = 0;
1369         p->cidcwexpire = 0;
1370         p->cidspill = malloc(MAX_CALLERID_SIZE);
1371         if (p->cidspill) {
1372                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
1373                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwaitcid, AST_LAW(p));
1374                 /* Make sure we account for the end */
1375                 p->cidlen += READ_SIZE * 4;
1376                 p->cidpos = 0;
1377                 send_callerid(p);
1378                 if (option_verbose > 2)
1379                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s'\n", p->callwaitcid);
1380         } else return -1;
1381         return 0;
1382 }
1383
1384 static int has_voicemail(struct zt_pvt *p)
1385 {
1386
1387         return ast_app_has_voicemail(p->mailbox);
1388 }
1389
1390 static int send_callerid(struct zt_pvt *p)
1391 {
1392         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1393         int res;
1394         /* Take out of linear mode if necessary */
1395         if (p->subs[SUB_REAL].linear) {
1396                 p->subs[SUB_REAL].linear = 0;
1397                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1398         }
1399         while(p->cidpos < p->cidlen) {
1400                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1401                 if (res < 0) {
1402                         if (errno == EAGAIN)
1403                                 return 0;
1404                         else {
1405                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1406                                 return -1;
1407                         }
1408                 }
1409                 if (!res)
1410                         return 0;
1411                 p->cidpos += res;
1412         }
1413         free(p->cidspill);
1414         p->cidspill = NULL;
1415         if (p->callwaitcas) {
1416                 /* Wait for CID/CW to expire */
1417                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1418         } else
1419                 restore_conference(p);
1420         return 0;
1421 }
1422
1423 static int zt_callwait(struct ast_channel *ast)
1424 {
1425         struct zt_pvt *p = ast->pvt->pvt;
1426         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1427         if (p->cidspill) {
1428                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1429                 free(p->cidspill);
1430         }
1431         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
1432         if (p->cidspill) {
1433                 save_conference(p);
1434                 /* Silence */
1435                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1436                 if (!p->callwaitrings && p->callwaitingcallerid) {
1437                         ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1438                         p->callwaitcas = 1;
1439                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
1440                 } else {
1441                         ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1442                         p->callwaitcas = 0;
1443                         p->cidlen = 2400 + READ_SIZE * 4;
1444                 }
1445                 p->cidpos = 0;
1446                 send_callerid(p);
1447         } else {
1448                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
1449                 return -1;
1450         }
1451         return 0;
1452 }
1453
1454 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1455 {
1456         struct zt_pvt *p = ast->pvt->pvt;
1457         int x, res, index;
1458         char *c, *n, *l;
1459 #ifdef ZAPATA_PRI
1460         char *s;
1461 #endif
1462         char callerid[256];
1463         char dest[256]; /* must be same length as p->dialdest */
1464         ast_mutex_lock(&p->lock);
1465         strncpy(dest, rdest, sizeof(dest) - 1);
1466         strncpy(p->dialdest, rdest, sizeof(dest) - 1);
1467         if ((ast->_state == AST_STATE_BUSY)) {
1468                 p->subs[SUB_REAL].needbusy = 1;
1469                 ast_mutex_unlock(&p->lock);
1470                 return 0;
1471         }
1472         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1473                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1474                 ast_mutex_unlock(&p->lock);
1475                 return -1;
1476         }
1477         p->dialednone = 0;
1478         if (p->radio)  /* if a radio channel, up immediately */
1479         {
1480                 /* Special pseudo -- automatically up */
1481                 ast_setstate(ast, AST_STATE_UP); 
1482                 ast_mutex_unlock(&p->lock);
1483                 return 0;
1484         }
1485         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1486         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1487         if (res)
1488                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1489         p->outgoing = 1;
1490
1491         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1492
1493         switch(p->sig) {
1494         case SIG_FXOLS:
1495         case SIG_FXOGS:
1496         case SIG_FXOKS:
1497                 if (p->owner == ast) {
1498                         /* Normal ring, on hook */
1499                         
1500                         /* Don't send audio while on hook, until the call is answered */
1501                         p->dialing = 1;
1502                         if (p->use_callerid) {
1503                                 /* Generate the Caller-ID spill if desired */
1504                                 if (p->cidspill) {
1505                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1506                                         free(p->cidspill);
1507                                 }
1508                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
1509                                 p->callwaitcas = 0;
1510                                 if (p->cidspill) {
1511                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->callerid, AST_LAW(p));
1512                                         p->cidpos = 0;
1513                                         send_callerid(p);
1514                                 } else
1515                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
1516                         }
1517                         /* Choose proper cadence */
1518                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1519                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1520                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1521                                 p->cidrings = cidrings[p->distinctivering - 1];
1522                         } else {
1523                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1524                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1525                                 p->cidrings = DEFAULT_CIDRINGS;
1526                         }
1527
1528
1529                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1530                         c = strchr(dest, '/');
1531                         if (c)
1532                                 c++;
1533                         if (c && (strlen(c) < p->stripmsd)) {
1534                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1535                                 c = NULL;
1536                         }
1537                         if (c) {
1538                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1539                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1540                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1541                         } else {
1542                                 p->dop.dialstr[0] = '\0';
1543                         }
1544                         x = ZT_RING;
1545                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1546                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1547                                 ast_mutex_unlock(&p->lock);
1548                                 return -1;
1549                         }
1550                         p->dialing = 1;
1551                 } else {
1552                         /* Call waiting call */
1553                         p->callwaitrings = 0;
1554                         if (ast->callerid)
1555                                 strncpy(p->callwaitcid, ast->callerid, sizeof(p->callwaitcid)-1);
1556                         else
1557                                 p->callwaitcid[0] = '\0';
1558                         /* Call waiting tone instead */
1559                         if (zt_callwait(ast)) {
1560                                 ast_mutex_unlock(&p->lock);
1561                                 return -1;
1562                         }
1563                         /* Make ring-back */
1564                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1565                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1566                                 
1567                 }
1568                 if (ast->callerid) 
1569                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1570                 else
1571                         callerid[0] = '\0';
1572                 ast_callerid_parse(callerid, &n, &l);
1573                 if (l) {
1574                         ast_shrink_phone_number(l);
1575                         if (!ast_isphonenumber(l))
1576                                 l = NULL;
1577                 }
1578                 if (l)
1579                         strncpy(p->lastcallerid, l, sizeof(p->lastcallerid) - 1);
1580                 else
1581                         p->lastcallerid[0] = '\0';
1582                 ast_setstate(ast, AST_STATE_RINGING);
1583                 index = zt_get_index(ast, p, 0);
1584                 if (index > -1) {
1585                         p->subs[index].needringing = 1;
1586                 }
1587                 break;
1588         case SIG_FXSLS:
1589         case SIG_FXSGS:
1590         case SIG_FXSKS:
1591         case SIG_EMWINK:
1592         case SIG_EM:
1593         case SIG_EM_E1:
1594         case SIG_FEATD:
1595         case SIG_FEATDMF:
1596         case SIG_E911:
1597         case SIG_FEATB:
1598         case SIG_SFWINK:
1599         case SIG_SF:
1600         case SIG_SF_FEATD:
1601         case SIG_SF_FEATDMF:
1602         case SIG_SF_FEATB:
1603                 c = strchr(dest, '/');
1604                 if (c)
1605                         c++;
1606                 else
1607                         c = "";
1608                 if (strlen(c) < p->stripmsd) {
1609                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1610                         ast_mutex_unlock(&p->lock);
1611                         return -1;
1612                 }
1613                 x = ZT_START;
1614                 /* Start the trunk */
1615                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1616                 if (res < 0) {
1617                         if (errno != EINPROGRESS) {
1618                                 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1619                                 ast_mutex_unlock(&p->lock);
1620                                 return -1;
1621                         }
1622                 }
1623                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1624                 p->dop.op = ZT_DIAL_OP_REPLACE;
1625                 if (p->sig == SIG_FEATD) {
1626                         if (ast->callerid) {
1627                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1628                                 ast_callerid_parse(callerid, &n, &l);
1629                                 if (l) {
1630                                         ast_shrink_phone_number(l);
1631                                         if (!ast_isphonenumber(l))
1632                                                 l = NULL;
1633                                 }
1634                         } else
1635                                 l = NULL;
1636                         if (l) 
1637                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1638                         else
1639                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1640                 } else 
1641                 if (p->sig == SIG_FEATDMF) {
1642                         if (ast->callerid) {
1643                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1644                                 ast_callerid_parse(callerid, &n, &l);
1645                                 if (l) {
1646                                         ast_shrink_phone_number(l);
1647                                         if (!ast_isphonenumber(l))
1648                                                 l = NULL;
1649                                 }
1650                         } else
1651                                 l = NULL;
1652                         if (l) 
1653                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1654                         else
1655                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1656                 } else 
1657                 if (p->sig == SIG_E911) {
1658                         strncpy(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr) - 1);
1659                 } else
1660                 if (p->sig == SIG_FEATB) {
1661                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1662                 } else 
1663                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c + p->stripmsd);
1664                 if (strlen(p->dop.dialstr) > 4) {
1665                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1666                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1667                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1668                         p->echobreak = 1;
1669                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1670                 } else
1671                         p->echobreak = 0;
1672                 if (!res) {
1673                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1674                                 x = ZT_ONHOOK;
1675                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1676                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1677                                 ast_mutex_unlock(&p->lock);
1678                                 return -1;
1679                         }
1680                 } else
1681                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1682                 p->dialing = 1;
1683                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1684                 ast_setstate(ast, AST_STATE_DIALING);
1685                 break;
1686         case 0:
1687                 /* Special pseudo -- automatically up*/
1688                 ast_setstate(ast, AST_STATE_UP);
1689                 break;          
1690         case SIG_PRI:
1691                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1692                 p->dialdest[0] = '\0';
1693                 break;
1694         default:
1695                 ast_log(LOG_DEBUG, "not yet implemented\n");
1696                 ast_mutex_unlock(&p->lock);
1697                 return -1;
1698         }
1699 #ifdef ZAPATA_PRI
1700         if (p->pri) {
1701                 struct pri_sr *sr;
1702                 c = strchr(dest, '/');
1703                 if (c)
1704                         c++;
1705                 else
1706                         c = dest;
1707                 if (ast->callerid && !p->hidecallerid) {
1708                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1709                         ast_callerid_parse(callerid, &n, &l);
1710                         if (l) {
1711                                 ast_shrink_phone_number(l);
1712                                 if (!ast_isphonenumber(l))
1713                                         l = NULL;
1714                         }
1715                 } else
1716                         l = NULL;
1717                 if (strlen(c) < p->stripmsd) {
1718                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1719                         ast_mutex_unlock(&p->lock);
1720                         return -1;
1721                 }
1722                 p->dop.op = ZT_DIAL_OP_REPLACE;
1723                 s = strchr(c + p->stripmsd, 'w');
1724                 if (s) {
1725                         if (strlen(s))
1726                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1727                         else
1728                                 p->dop.dialstr[0] = '\0';
1729                         *s = '\0';
1730                 } else {
1731                         p->dop.dialstr[0] = '\0';
1732                 }
1733                 if (pri_grab(p, p->pri)) {
1734                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1735                         ast_mutex_unlock(&p->lock);
1736                         return -1;
1737                 }
1738                 if (!(p->call = pri_new_call(p->pri->pri))) {
1739                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1740                         pri_rel(p->pri);
1741                         ast_mutex_unlock(&p->lock);
1742                         return -1;
1743                 }
1744                 if (!(sr = pri_sr_new())) {
1745                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1746                         pri_rel(p->pri);
1747                         ast_mutex_unlock(&p->lock);
1748                 }
1749                 if (p->bearer) {
1750                         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);
1751                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1752                         p->bearer->call = p->call;
1753                 }
1754                 p->digital = ast_test_flag(ast,AST_FLAG_DIGITAL);
1755                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1756                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1757                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : PRI_TRANS_CAP_SPEECH, 
1758                                         (p->digital ? -1 : 
1759                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1760                 pri_sr_set_called(sr, c + p->stripmsd, p->pri->dialplan - 1,  s ? 1 : 0);
1761                 pri_sr_set_caller(sr, l, n, p->pri->localdialplan - 1, 
1762                                         l ? (ast->restrictcid ? PRES_PROHIB_USER_NUMBER_PASSED_SCREEN : 
1763                                                 (p->use_callingpres ? ast->callingpres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN)) : 
1764                                                  PRES_NUMBER_NOT_AVAILABLE);
1765                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1766                         ast_log(LOG_WARNING, "Unable to setup call to %s\n", c + p->stripmsd);
1767                         pri_rel(p->pri);
1768                         ast_mutex_unlock(&p->lock);
1769                         pri_sr_free(sr);
1770                         return -1;
1771                 }
1772                 pri_sr_free(sr);
1773                 ast_setstate(ast, AST_STATE_DIALING);
1774                 pri_rel(p->pri);
1775         }
1776 #endif          
1777         ast_mutex_unlock(&p->lock);
1778         return 0;
1779 }
1780
1781 static void destroy_zt_pvt(struct zt_pvt **pvt)
1782 {
1783         struct zt_pvt *p = *pvt;
1784         ast_mutex_destroy(&p->lock);
1785         free(p);
1786         *pvt = NULL;
1787 }
1788
1789 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1790 {
1791         int owned = 0;
1792         int i = 0;
1793
1794         if (!now) {
1795                 if (cur->owner) {
1796                         owned = 1;
1797                 }
1798
1799                 for (i = 0; i < 3; i++) {
1800                         if (cur->subs[i].owner) {
1801                                 owned = 1;
1802                         }
1803                 }
1804                 if (!owned) {
1805                         if (prev) {
1806                                 prev->next = cur->next;
1807                                 if (prev->next)
1808                                         prev->next->prev = prev;
1809                                 else
1810                                         ifend = prev;
1811                         } else {
1812                                 iflist = cur->next;
1813                                 if (iflist)
1814                                         iflist->prev = NULL;
1815                                 else
1816                                         ifend = NULL;
1817                         }
1818                         if (cur->subs[SUB_REAL].zfd > -1) {
1819                                 zt_close(cur->subs[SUB_REAL].zfd);
1820                         }
1821                         destroy_zt_pvt(&cur);
1822                 }
1823         } else {
1824                 if (prev) {
1825                         prev->next = cur->next;
1826                         if (prev->next)
1827                                 prev->next->prev = prev;
1828                         else
1829                                 ifend = prev;
1830                 } else {
1831                         iflist = cur->next;
1832                         if (iflist)
1833                                 iflist->prev = NULL;
1834                         else
1835                                 ifend = NULL;
1836                 }
1837                 if (cur->subs[SUB_REAL].zfd > -1) {
1838                         zt_close(cur->subs[SUB_REAL].zfd);
1839                 }
1840                 destroy_zt_pvt(&cur);
1841         }
1842         return 0;
1843 }
1844
1845 #ifdef ZAPATA_PRI
1846 int pri_is_up(struct zt_pri *pri)
1847 {
1848         int x;
1849         for (x=0;x<NUM_DCHANS;x++) {
1850                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
1851                         return 1;
1852         }
1853         return 0;
1854 }
1855
1856 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
1857 {
1858         bearer->owner = &inuse;
1859         bearer->master = crv;
1860         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
1861         crv->bearer = bearer;
1862         crv->call = bearer->call;
1863         crv->pri = pri;
1864         return 0;
1865 }
1866
1867 static char *pri_order(int level)
1868 {
1869         switch(level) {
1870         case 0:
1871                 return "Primary";
1872         case 1:
1873                 return "Secondary";
1874         case 2:
1875                 return "Tertiary";
1876         case 3:
1877                 return "Quaternary";
1878         default:
1879                 return "<Unknown>";
1880         }               
1881 }
1882
1883 int pri_find_dchan(struct zt_pri *pri)
1884 {
1885         int oldslot = -1;
1886         struct pri *old;
1887         int newslot = -1;
1888         int x;
1889         old = pri->pri;
1890         for(x=0;x<NUM_DCHANS;x++) {
1891                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
1892                         newslot = x;
1893                 if (pri->dchans[x] == old) {
1894                         oldslot = x;
1895                 }
1896         }
1897         if (newslot < 0) {
1898                 newslot = 0;
1899                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
1900                         pri->dchannels[newslot]);
1901         }
1902         if (old && (oldslot != newslot))
1903                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
1904                         pri->dchannels[oldslot], pri->dchannels[newslot]);
1905         pri->pri = pri->dchans[newslot];
1906         return 0;
1907 }
1908 #endif
1909
1910 static int zt_hangup(struct ast_channel *ast)
1911 {
1912         int res;
1913         int index,x, law;
1914         static int restore_gains(struct zt_pvt *p);
1915         struct zt_pvt *p = ast->pvt->pvt;
1916         struct zt_pvt *tmp = NULL;
1917         struct zt_pvt *prev = NULL;
1918         ZT_PARAMS par;
1919
1920         if (option_debug)
1921                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1922         if (!ast->pvt->pvt) {
1923                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1924                 return 0;
1925         }
1926         
1927         ast_mutex_lock(&p->lock);
1928         
1929         index = zt_get_index(ast, p, 1);
1930
1931         if (p->sig == SIG_PRI) {
1932                 x = 1;
1933                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
1934         }
1935
1936         x = 0;
1937         zt_confmute(p, 0);
1938         restore_gains(p);
1939         if (p->origcallerid) {
1940                 strncpy(p->callerid, p->origcallerid, sizeof(p->callerid) - 1);
1941                 free(p->origcallerid);
1942                 p->origcallerid = NULL;
1943         }       
1944         if (p->dsp)
1945                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
1946         if (p->exten)
1947                 p->exten[0] = '\0';
1948
1949         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1950                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
1951         p->ignoredtmf = 0;
1952         
1953         if (index > -1) {
1954                 /* Real channel, do some fixup */
1955                 p->subs[index].owner = NULL;
1956                 p->subs[index].needanswer = 0;
1957                 p->subs[index].needringing = 0;
1958                 p->subs[index].needbusy = 0;
1959                 p->subs[index].needcongestion = 0;
1960                 p->subs[index].linear = 0;
1961                 p->subs[index].needcallerid = 0;
1962                 zt_setlinear(p->subs[index].zfd, 0);
1963                 if (index == SUB_REAL) {
1964                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
1965                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
1966                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
1967                                         /* We had flipped over to answer a callwait and now it's gone */
1968                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
1969                                         /* Move to the call-wait, but un-own us until they flip back. */
1970                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1971                                         unalloc_sub(p, SUB_CALLWAIT);
1972                                         p->owner = NULL;
1973                                 } else {
1974                                         /* The three way hung up, but we still have a call wait */
1975                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1976                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
1977                                         unalloc_sub(p, SUB_THREEWAY);
1978                                         if (p->subs[SUB_REAL].inthreeway) {
1979                                                 /* This was part of a three way call.  Immediately make way for
1980                                                    another call */
1981                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1982                                                 p->owner = p->subs[SUB_REAL].owner;
1983                                         } else {
1984                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1985                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1986                                                 p->owner = NULL;
1987                                         }
1988                                         p->subs[SUB_REAL].inthreeway = 0;
1989                                 }
1990                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
1991                                 /* Move to the call-wait and switch back to them. */
1992                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1993                                 unalloc_sub(p, SUB_CALLWAIT);
1994                                 p->owner = p->subs[SUB_REAL].owner;
1995                                 if (p->owner->_state != AST_STATE_UP)
1996                                         p->subs[SUB_REAL].needanswer = 1;
1997                                 if (p->subs[SUB_REAL].owner->bridge)
1998                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
1999                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
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 (index == SUB_CALLWAIT) {
2015                         /* Ditch the holding callwait call, and immediately make it availabe */
2016                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2017                                 /* This is actually part of a three way, placed on hold.  Place the third part
2018                                    on music on hold now */
2019                                 if (p->subs[SUB_THREEWAY].owner && p->subs[SUB_THREEWAY].owner->bridge)
2020                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
2021                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2022                                 /* Make it the call wait now */
2023                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2024                                 unalloc_sub(p, SUB_THREEWAY);
2025                         } else
2026                                 unalloc_sub(p, SUB_CALLWAIT);
2027                 } else if (index == SUB_THREEWAY) {
2028                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2029                                 /* The other party of the three way call is currently in a call-wait state.
2030                                    Start music on hold for them, and take the main guy out of the third call */
2031                                 if (p->subs[SUB_CALLWAIT].owner && p->subs[SUB_CALLWAIT].owner->bridge)
2032                                         ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
2033                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2034                         }
2035                         p->subs[SUB_REAL].inthreeway = 0;
2036                         /* If this was part of a three way call index, let us make
2037                            another three way call */
2038                         unalloc_sub(p, SUB_THREEWAY);
2039                 } else {
2040                         /* This wasn't any sort of call, but how are we an index? */
2041                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2042                 }
2043         }
2044
2045
2046         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2047                 p->owner = NULL;
2048                 p->ringt = 0;
2049                 p->distinctivering = 0;
2050                 p->confirmanswer = 0;
2051                 p->cidrings = 1;
2052                 p->outgoing = 0;
2053                 p->digital = 0;
2054                 p->faxhandled = 0;
2055                 p->pulsedial = 0;
2056                 p->onhooktime = time(NULL);
2057 #ifdef ZAPATA_PRI
2058                 p->proceeding = 0;
2059                 p->setup_ack = 0;
2060 #endif          
2061                 if (p->dsp) {
2062                         ast_dsp_free(p->dsp);
2063                         p->dsp = NULL;
2064                 }
2065
2066                 law = ZT_LAW_DEFAULT;
2067                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2068                 if (res < 0) 
2069                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2070                 /* Perform low level hangup if no owner left */
2071 #ifdef ZAPATA_PRI
2072                 if (p->pri) {
2073                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2074                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2075                                 if (!pri_grab(p, p->pri)) {
2076                                         if (p->alreadyhungup) {
2077                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2078                                                 pri_hangup(p->pri->pri, p->call, -1);
2079                                                 p->call = NULL;
2080                                                 if (p->bearer) 
2081                                                         p->bearer->call = NULL;
2082                                         } else {
2083                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2084                                                 int icause = ast->hangupcause ? hangup_cause2pri(ast->hangupcause) : -1;
2085                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2086                                                 p->alreadyhungup = 1;
2087                                                 if (p->bearer)
2088                                                         p->bearer->alreadyhungup = 1;
2089                                                 if (cause) {
2090                                                         if (atoi(cause))
2091                                                                 icause = atoi(cause);
2092                                                 }
2093                                                 pri_hangup(p->pri->pri, p->call, icause);
2094                                         }
2095                                         if (res < 0) 
2096                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2097                                         pri_rel(p->pri);                        
2098                                 } else {
2099                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2100                                         res = -1;
2101                                 }
2102                         } else {
2103                                 if (p->bearer)
2104                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2105                                 p->call = NULL;
2106                                 res = 0;
2107                         }
2108                 }
2109 #endif
2110 #ifdef ZAPATA_R2
2111                 if (p->sig == SIG_R2) {
2112                         if (p->hasr2call) {
2113                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2114                                 p->hasr2call = 0;
2115                                 res = 0;
2116                         } else
2117                                 res = 0;
2118
2119                 }
2120 #endif
2121                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2122                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2123                 if (res < 0) {
2124                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2125                 }
2126                 switch(p->sig) {
2127                 case SIG_FXOGS:
2128                 case SIG_FXOLS:
2129                 case SIG_FXOKS:
2130                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2131                         if (!res) {
2132 #if 0
2133                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2134 #endif
2135                                 /* If they're off hook, try playing congestion */
2136                                 if (par.rxisoffhook)
2137                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2138                                 else
2139                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2140                         }
2141                         break;
2142                 case SIG_FXSGS:
2143                 case SIG_FXSLS:
2144                 case SIG_FXSKS:
2145                         /* Make sure we're not made available for at least two seconds */
2146                         time(&p->guardtime);
2147                         p->guardtime += 2;
2148                         break;
2149                 default:
2150                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2151                 }
2152                 if (p->cidspill)
2153                         free(p->cidspill);
2154                 if (p->sig)
2155                         zt_disable_ec(p);
2156                 x = 0;
2157                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2158                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2159                 p->didtdd = 0;
2160                 p->cidspill = NULL;
2161                 p->callwaitcas = 0;
2162                 p->callwaiting = p->permcallwaiting;
2163                 p->hidecallerid = p->permhidecallerid;
2164                 p->dialing = 0;
2165                 p->rdnis[0] = '\0';
2166                 update_conf(p);
2167                 /* Restore data mode */
2168                 if (p->sig == SIG_PRI) {
2169                         x = 0;
2170                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2171                 }
2172 #ifdef ZAPATA_PRI
2173                 if (p->bearer) {
2174                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2175                         /* Free up the bearer channel as well, and
2176                            don't use its file descriptor anymore */
2177                         p->bearer->owner = NULL;
2178                         p->bearer = NULL;
2179                         p->subs[SUB_REAL].zfd = -1;
2180                         p->pri = NULL;
2181                 }
2182 #endif
2183                 restart_monitor();
2184         }
2185
2186
2187         p->callwaitingrepeat = 0;
2188         p->cidcwexpire = 0;
2189         ast->pvt->pvt = NULL;
2190         ast_mutex_unlock(&p->lock);
2191         ast_mutex_lock(&usecnt_lock);
2192         usecnt--;
2193         if (usecnt < 0) 
2194                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2195         ast_mutex_unlock(&usecnt_lock);
2196         ast_update_use_count();
2197         if (option_verbose > 2) 
2198                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2199
2200         ast_mutex_lock(&iflock);
2201         tmp = iflist;
2202         prev = NULL;
2203         if (p->destroy) {
2204                 while (tmp) {
2205                         if (tmp == p) {
2206                                 destroy_channel(prev, tmp, 0);
2207                                 break;
2208                         } else {
2209                                 prev = tmp;
2210                                 tmp = tmp->next;
2211                         }
2212                 }
2213         }
2214         ast_mutex_unlock(&iflock);
2215         return 0;
2216 }
2217
2218 static int zt_answer(struct ast_channel *ast)
2219 {
2220         struct zt_pvt *p = ast->pvt->pvt;
2221         int res=0;
2222         int index;
2223         int oldstate = ast->_state;
2224         ast_setstate(ast, AST_STATE_UP);
2225         ast_mutex_lock(&p->lock);
2226         index = zt_get_index(ast, p, 0);
2227         if (index < 0)
2228                 index = SUB_REAL;
2229         /* nothing to do if a radio channel */
2230         if (p->radio) {
2231                 ast_mutex_unlock(&p->lock);
2232                 return 0;
2233         }
2234         switch(p->sig) {
2235         case SIG_FXSLS:
2236         case SIG_FXSGS:
2237         case SIG_FXSKS:
2238                 p->ringt = 0;
2239                 /* Fall through */
2240         case SIG_EM:
2241         case SIG_EM_E1:
2242         case SIG_EMWINK:
2243         case SIG_FEATD:
2244         case SIG_FEATDMF:
2245         case SIG_E911:
2246         case SIG_FEATB:
2247         case SIG_SF:
2248         case SIG_SFWINK:
2249         case SIG_SF_FEATD:
2250         case SIG_SF_FEATDMF:
2251         case SIG_SF_FEATB:
2252         case SIG_FXOLS:
2253         case SIG_FXOGS:
2254         case SIG_FXOKS:
2255                 /* Pick up the line */
2256                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2257                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2258                 tone_zone_play_tone(p->subs[index].zfd, -1);
2259                 p->dialing = 0;
2260                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2261                         if (oldstate == AST_STATE_RINGING) {
2262                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2263                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2264                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2265                                 p->owner = p->subs[SUB_REAL].owner;
2266                         }
2267                 }
2268                 if (p->sig & __ZT_SIG_FXS) {
2269                         zt_enable_ec(p);
2270                         zt_train_ec(p);
2271                 }
2272                 break;
2273 #ifdef ZAPATA_PRI
2274         case SIG_PRI:
2275                 /* Send a pri acknowledge */
2276                 if (!pri_grab(p, p->pri)) {
2277                         p->proceeding = 2;
2278                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2279                         pri_rel(p->pri);
2280                 } else {
2281                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2282                         res= -1;
2283                 }
2284                 break;
2285 #endif
2286 #ifdef ZAPATA_R2
2287         case SIG_R2:
2288                 res = mfcr2_AnswerCall(p->r2, NULL);
2289                 if (res)
2290                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2291                 break;
2292 #endif                  
2293         case 0:
2294                 ast_mutex_unlock(&p->lock);
2295                 return 0;
2296         default:
2297                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2298                 res = -1;
2299         }
2300         ast_mutex_unlock(&p->lock);
2301         return res;
2302 }
2303
2304 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2305 {
2306 char    *cp;
2307 int     x;
2308
2309         struct zt_pvt *p = chan->pvt->pvt;
2310
2311         
2312         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2313                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2314            {
2315                 errno = ENOSYS;
2316                 return -1;
2317            }
2318         cp = (char *)data;
2319         if ((!cp) || (datalen < 1))
2320            {
2321                 errno = EINVAL;
2322                 return -1;
2323            }
2324         switch(option) {
2325             case AST_OPTION_TONE_VERIFY:
2326                 if (!p->dsp)
2327                         break;
2328                 switch(*cp) {
2329                     case 1:
2330                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2331                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2332                         break;
2333                     case 2:
2334                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2335                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2336                         break;
2337                     default:
2338                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2339                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2340                         break;
2341                 }
2342                 break;
2343             case AST_OPTION_TDD:  /* turn on or off TDD */
2344                 if (!*cp) { /* turn it off */
2345                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2346                         if (p->tdd) tdd_free(p->tdd);
2347                         p->tdd = 0;
2348                         p->mate = 0;
2349                         break;
2350                 }
2351                 if (*cp == 2)
2352                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2353                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2354                 p->mate = 0;
2355                 zt_disable_ec(p);
2356                 /* otherwise, turn it on */
2357                 if (!p->didtdd) { /* if havent done it yet */
2358                         unsigned char mybuf[41000],*buf;
2359                         int size,res,fd,len;
2360                         int index;
2361                         struct pollfd fds[1];
2362                         buf = mybuf;
2363                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2364                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2365                         len = 40000;
2366                         index = zt_get_index(chan, p, 0);
2367                         if (index < 0) {
2368                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2369                                 return -1;
2370                         }
2371                         fd = p->subs[index].zfd;
2372                         while(len) {
2373                                 if (ast_check_hangup(chan)) return -1;
2374                                 size = len;
2375                                 if (size > READ_SIZE)
2376                                         size = READ_SIZE;
2377                                 fds[0].fd = fd;
2378                                 fds[0].events = POLLPRI | POLLOUT;
2379                                 res = poll(fds, 1, -1);
2380                                 if (!res) {
2381                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2382                                         continue;
2383                                 }
2384                                   /* if got exception */
2385                                 if (fds[0].revents & POLLPRI) return -1;
2386                                 if (!(fds[0].revents & POLLOUT)) {
2387                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2388                                         continue;
2389                                 }
2390                                 res = write(fd, buf, size);
2391                                 if (res != size) {
2392                                         if (res == -1) return -1;
2393                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2394                                         break;
2395                                 }
2396                                 len -= size;
2397                                 buf += size;
2398                         }
2399                         p->didtdd = 1; /* set to have done it now */            
2400                 }
2401                 if (*cp == 2) { /* Mate mode */
2402                         if (p->tdd) tdd_free(p->tdd);
2403                         p->tdd = 0;
2404                         p->mate = 1;
2405                         break;
2406                         }               
2407                 if (!p->tdd) { /* if we dont have one yet */
2408                         p->tdd = tdd_new(); /* allocate one */
2409                 }               
2410                 break;
2411             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2412                 if (!*cp)
2413                 {               
2414                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2415                         x = 0;
2416                 }
2417                 else
2418                 {               
2419                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2420                         x = 1;
2421                 }
2422                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2423                 break;
2424             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2425                 if (!*cp)
2426                 {               
2427                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2428                         x = 0;
2429                         zt_disable_ec(p);
2430                 }
2431                 else
2432                 {               
2433                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2434                         x = 1;
2435                 }
2436                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2437                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2438                 break;
2439         }
2440         errno = 0;
2441         return 0;
2442 }
2443
2444 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2445 {
2446         /* Unlink a specific slave or all slaves/masters from a given master */
2447         int x;
2448         int hasslaves;
2449         if (!master)
2450                 return;
2451         if (needlock) {
2452                 ast_mutex_lock(&master->lock);
2453                 if (slave) {
2454                         while(ast_mutex_trylock(&slave->lock)) {
2455                                 ast_mutex_unlock(&master->lock);
2456                                 usleep(1);
2457                                 ast_mutex_lock(&master->lock);
2458                         }
2459                 }
2460         }
2461         hasslaves = 0;
2462         for (x=0;x<MAX_SLAVES;x++) {
2463                 if (master->slaves[x]) {
2464                         if (!slave || (master->slaves[x] == slave)) {
2465                                 /* Take slave out of the conference */
2466                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2467                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2468                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2469                                 master->slaves[x]->master = NULL;
2470                                 master->slaves[x] = NULL;
2471                         } else
2472                                 hasslaves = 1;
2473                 }
2474                 if (!hasslaves)
2475                         master->inconference = 0;
2476         }
2477         if (!slave) {
2478                 if (master->master) {
2479                         /* Take master out of the conference */
2480                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2481                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2482                         hasslaves = 0;
2483                         for (x=0;x<MAX_SLAVES;x++) {
2484                                 if (master->master->slaves[x] == master)
2485                                         master->master->slaves[x] = NULL;
2486                                 else if (master->master->slaves[x])
2487                                         hasslaves = 1;
2488                         }
2489                         if (!hasslaves)
2490                                 master->master->inconference = 0;
2491                 }
2492                 master->master = NULL;
2493         }
2494         update_conf(master);
2495         if (needlock) {
2496                 if (slave)
2497                         ast_mutex_unlock(&slave->lock);
2498                 ast_mutex_unlock(&master->lock);
2499         }
2500 }
2501
2502 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2503         int x;
2504         if (!slave || !master) {
2505                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2506                 return;
2507         }
2508         for (x=0;x<MAX_SLAVES;x++) {
2509                 if (!master->slaves[x]) {
2510                         master->slaves[x] = slave;
2511                         break;
2512                 }
2513         }
2514         if (x >= MAX_SLAVES) {
2515                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2516                 master->slaves[MAX_SLAVES - 1] = slave;
2517         }
2518         if (slave->master) 
2519                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2520         slave->master = master;
2521         
2522         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2523 }
2524
2525 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2526 {
2527         struct ast_channel *who = NULL, *cs[3];
2528         struct zt_pvt *p0, *p1, *op0, *op1;
2529         struct zt_pvt *master=NULL, *slave=NULL;
2530         struct ast_frame *f;
2531         int to;
2532         int inconf = 0;
2533         int nothingok = 0;
2534         int ofd1, ofd2;
2535         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2536         int os1 = -1, os2 = -1;
2537         struct ast_channel *oc1, *oc2;
2538
2539         /* if need DTMF, cant native bridge */
2540         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2541                 return -2;
2542                 
2543         ast_mutex_lock(&c0->lock);
2544         ast_mutex_lock(&c1->lock);
2545
2546         p0 = c0->pvt->pvt;
2547         p1 = c1->pvt->pvt;
2548         /* cant do pseudo-channels here */
2549         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2550                 ast_mutex_unlock(&c0->lock);
2551                 ast_mutex_unlock(&c1->lock);
2552                 return -2;
2553         }
2554
2555         op0 = p0 = c0->pvt->pvt;
2556         op1 = p1 = c1->pvt->pvt;
2557         ofd1 = c0->fds[0];
2558         ofd2 = c1->fds[0];
2559         oi1 = zt_get_index(c0, p0, 0);
2560         oi2 = zt_get_index(c1, p1, 0);
2561         oc1 = p0->owner;
2562         oc2 = p1->owner;
2563         if ((oi1 < 0) || (oi2 < 0)) {
2564                 ast_mutex_unlock(&c0->lock);
2565                 ast_mutex_unlock(&c1->lock);
2566                 return -1;
2567         }
2568
2569
2570
2571         ast_mutex_lock(&p0->lock);
2572         if (ast_mutex_trylock(&p1->lock)) {
2573                 /* Don't block, due to potential for deadlock */
2574                 ast_mutex_unlock(&p0->lock);
2575                 ast_mutex_unlock(&c0->lock);
2576                 ast_mutex_unlock(&c1->lock);
2577                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2578                 return -3;
2579         }
2580         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2581                 if (!p0->owner || !p1->owner) {
2582                         /* Currently unowned -- Do nothing.  */
2583                         nothingok = 1;
2584                 } else {
2585                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2586                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2587                                 master = p0;
2588                                 slave = p1;
2589                                 inconf = 1;
2590                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2591                                 master = p1;
2592                                 slave = p0;
2593                                 inconf = 1;
2594                         } else {
2595                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2596                                 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,
2597                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2598                         }
2599                 }
2600         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2601                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2602                         master = p1;
2603                         slave = p0;
2604                 } else {
2605                         nothingok = 1;
2606                 }
2607         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2608                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2609                         master = p0;
2610                         slave = p1;
2611                 } else {
2612                         nothingok  = 1;
2613                 }
2614         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2615                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2616                    don't put us in anything */
2617                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2618                         master = p1;
2619                         slave = p0;
2620                 } else {
2621                         nothingok = 1;
2622                 }
2623         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2624                 /* Same as previous */
2625                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2626                         master = p0;
2627                         slave = p1;
2628                 } else {
2629                         nothingok = 1;
2630                 }
2631         }
2632         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2633                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2634         if (master && slave) {
2635                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2636                    in an active threeway call with a channel that is ringing, we should
2637                    indicate ringing. */
2638                 if ((oi2 == SUB_THREEWAY) && 
2639                         p1->subs[SUB_THREEWAY].inthreeway && 
2640                         p1->subs[SUB_REAL].owner && 
2641                         p1->subs[SUB_REAL].inthreeway && 
2642                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2643                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2644                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2645                                 os2 = p1->subs[SUB_REAL].owner->_state;
2646                 } else {
2647                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2648                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2649                 }
2650                 if ((oi1 == SUB_THREEWAY) && 
2651                         p0->subs[SUB_THREEWAY].inthreeway && 
2652                         p0->subs[SUB_REAL].owner && 
2653                         p0->subs[SUB_REAL].inthreeway && 
2654                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2655                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2656                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2657                                 os1 = p0->subs[SUB_REAL].owner->_state;
2658                 } else {
2659                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2660                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2661                 }
2662                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2663                         if (!p0->echocanbridged || !p1->echocanbridged) {
2664                                 /* Disable echo cancellation if appropriate */
2665                                 zt_disable_ec(p0);
2666                                 zt_disable_ec(p1);
2667                         }
2668                 }
2669                 zt_link(slave, master);
2670                 master->inconference = inconf;
2671         } else if (!nothingok)
2672                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2673
2674         update_conf(p0);
2675         update_conf(p1);
2676         t1 = p0->subs[SUB_REAL].inthreeway;
2677         t2 = p1->subs[SUB_REAL].inthreeway;
2678
2679         ast_mutex_unlock(&p0->lock);
2680         ast_mutex_unlock(&p1->lock);
2681
2682         ast_mutex_unlock(&c0->lock);
2683         ast_mutex_unlock(&c1->lock);
2684
2685         /* Native bridge failed */
2686         if ((!master || !slave) && !nothingok) {
2687                 if (op0 == p0)
2688                         zt_enable_ec(p0);
2689                 if (op1 == p1)
2690                         zt_enable_ec(p1);
2691                 return -1;
2692         }
2693         
2694         cs[0] = c0;
2695         cs[1] = c1;
2696         cs[2] = NULL;
2697         for (;;) {
2698                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2699                    and then balking if anything is wrong */
2700                 ast_mutex_lock(&c0->lock);
2701                 ast_mutex_lock(&c1->lock);
2702                 p0 = c0->pvt->pvt;
2703                 p1 = c1->pvt->pvt;
2704                 if (op0 == p0)
2705                         i1 = zt_get_index(c0, p0, 1);
2706                 if (op1 == p1)
2707                         i2 = zt_get_index(c1, p1, 1);
2708                 ast_mutex_unlock(&c0->lock);
2709                 ast_mutex_unlock(&c1->lock);
2710                 if ((op0 != p0) || (op1 != p1) || 
2711                     (ofd1 != c0->fds[0]) || 
2712                         (ofd2 != c1->fds[0]) ||
2713                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2714                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2715                     (oc1 != p0->owner) || 
2716                         (oc2 != p1->owner) ||
2717                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2718                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2719                         (oi1 != i1) ||
2720                         (oi2 != i2)) {
2721                         if (slave && master)
2722                                 zt_unlink(slave, master, 1);
2723                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2724                                                                         op0->channel, oi1, op1->channel, oi2);
2725                         if (op0 == p0)
2726                                 zt_enable_ec(p0);
2727                         if (op1 == p1)
2728                                 zt_enable_ec(p1);
2729                         return -3;
2730                 }
2731                 to = -1;
2732                 who = ast_waitfor_n(cs, 2, &to);
2733                 if (!who) {
2734                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2735                         continue;
2736                 }
2737                 if (who->pvt->pvt == op0) 
2738                         op0->ignoredtmf = 1;
2739                 else if (who->pvt->pvt == op1)
2740                         op1->ignoredtmf = 1;
2741                 f = ast_read(who);
2742                 if (who->pvt->pvt == op0) 
2743                         op0->ignoredtmf = 0;
2744                 else if (who->pvt->pvt == op1)
2745                         op1->ignoredtmf = 0;
2746                 if (!f) {
2747                         *fo = NULL;
2748                         *rc = who;
2749                         if (slave && master)
2750                                 zt_unlink(slave, master, 1);
2751                         if (op0 == p0)
2752                                 zt_enable_ec(p0);
2753                         if (op1 == p1)
2754                                 zt_enable_ec(p1);
2755                         return 0;
2756                 }
2757                 if (f->frametype == AST_FRAME_DTMF) {
2758                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2759                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2760                                 *fo = f;
2761                                 *rc = who;
2762                                 if (slave && master)
2763                                         zt_unlink(slave, master, 1);
2764                                 return 0;
2765                         } else if ((who == c0) && p0->pulsedial) {
2766                                 ast_write(c1, f);
2767                         } else if ((who == c1) && p1->pulsedial) {
2768                                 ast_write(c0, f);
2769                         }
2770                 }
2771                 ast_frfree(f);
2772
2773                 /* Swap who gets priority */
2774                 cs[2] = cs[0];
2775                 cs[0] = cs[1];
2776                 cs[1] = cs[2];
2777         }
2778 }
2779
2780 static int zt_indicate(struct ast_channel *chan, int condition);
2781
2782 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2783 {
2784         struct zt_pvt *p = newchan->pvt->pvt;
2785         int x;
2786         ast_mutex_lock(&p->lock);
2787         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2788         if (p->owner == oldchan) {
2789                 p->owner = newchan;
2790         }
2791         for (x=0;x<3;x++)
2792                 if (p->subs[x].owner == oldchan) {
2793                         if (!x)
2794                                 zt_unlink(NULL, p, 0);
2795                         p->subs[x].owner = newchan;
2796                 }
2797         if (newchan->_state == AST_STATE_RINGING) 
2798                 zt_indicate(newchan, AST_CONTROL_RINGING);
2799         update_conf(p);
2800         ast_mutex_unlock(&p->lock);
2801         return 0;
2802 }
2803
2804 static int zt_ring_phone(struct zt_pvt *p)
2805 {
2806         int x;
2807         int res;
2808         /* Make sure our transmit state is on hook */
2809         x = 0;
2810         x = ZT_ONHOOK;
2811         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2812         do {
2813                 x = ZT_RING;
2814                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2815 #if 0
2816                 printf("Res: %d, error: %s\n", res, strerror(errno));
2817 #endif                                          
2818                 if (res) {
2819                         switch(errno) {
2820                         case EBUSY:
2821                         case EINTR:
2822                                 /* Wait just in case */
2823                                 usleep(10000);
2824                                 continue;
2825                         case EINPROGRESS:
2826                                 res = 0;
2827                                 break;
2828                         default:
2829                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2830                                 res = 0;
2831                         }
2832                 }
2833         } while (res);
2834         return res;
2835 }
2836
2837 static void *ss_thread(void *data);
2838
2839 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2840
2841 static int attempt_transfer(struct zt_pvt *p)
2842 {
2843         /* In order to transfer, we need at least one of the channels to
2844            actually be in a call bridge.  We can't conference two applications
2845            together (but then, why would we want to?) */
2846         if (p->subs[SUB_REAL].owner->bridge) {
2847                 /* The three-way person we're about to transfer to could still be in MOH, so
2848                    stop if now if appropriate */
2849                 if (p->subs[SUB_THREEWAY].owner->bridge)
2850                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2851                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2852                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2853                 }
2854                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2855                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2856                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2857                         return -1;
2858                 }
2859                 /* Orphan the channel */
2860                 unalloc_sub(p, SUB_THREEWAY);
2861         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2862                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2863                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2864                 }
2865                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2866                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2867                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2868                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2869                         return -1;
2870                 }
2871                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2872                 unalloc_sub(p, SUB_THREEWAY);
2873                 /* Tell the caller not to hangup */
2874                 return 1;
2875         } else {
2876                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2877                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2878                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2879         }
2880         return 0;
2881 }
2882
2883 #ifdef ZAPATA_R2
2884 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2885 {
2886         struct ast_frame *f;
2887         f = &p->subs[index].f;
2888         if (!p->r2) {
2889                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2890                 return NULL;
2891         }
2892         switch(e->e) {
2893         case MFCR2_EVENT_BLOCKED:
2894                 if (option_verbose > 2)
2895                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2896                 break;
2897         case MFCR2_EVENT_UNBLOCKED:
2898                 if (option_verbose > 2)
2899                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2900                 break;
2901         case MFCR2_EVENT_CONFIG_ERR:
2902                 if (option_verbose > 2)
2903                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2904                 break;
2905         case MFCR2_EVENT_RING:
2906                 if (option_verbose > 2)
2907                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2908                 break;
2909         case MFCR2_EVENT_HANGUP:
2910                 if (option_verbose > 2)
2911                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2912                 break;
2913         case MFCR2_EVENT_RINGING:
2914                 if (option_verbose > 2)
2915                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2916                 break;
2917         case MFCR2_EVENT_ANSWER:
2918                 if (option_verbose > 2)
2919                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2920                 break;
2921         case MFCR2_EVENT_HANGUP_ACK:
2922                 if (option_verbose > 2)
2923                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2924                 break;
2925         case MFCR2_EVENT_IDLE:
2926                 if (option_verbose > 2)
2927                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2928                 break;
2929         default:
2930                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2931                 break;
2932         }
2933         return f;
2934 }
2935
2936 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2937 {
2938         int x;
2939         int res;
2940         mfcr2_event_t *e;
2941         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2942         if (res) {
2943                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2944                 return NULL;
2945         }
2946         if (!p->r2) {
2947                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2948                 return NULL;
2949         }
2950         e = mfcr2_cas_signaling_event(p->r2, x);
2951         return e;
2952 }
2953 #endif
2954
2955 static int check_for_conference(struct zt_pvt *p)
2956 {
2957         ZT_CONFINFO ci;
2958         /* Fine if we already have a master, etc */
2959         if (p->master || (p->confno > -1))
2960                 return 0;
2961         memset(&ci, 0, sizeof(ci));
2962         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2963                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2964                 return 0;
2965         }
2966         /* If we have no master and don't have a confno, then 
2967            if we're in a conference, it's probably a MeetMe room or
2968            some such, so don't let us 3-way out! */
2969         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
2970                 if (option_verbose > 2) 
2971                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2972                 return 1;
2973         }
2974         return 0;
2975 }
2976
2977 static int get_alarms(struct zt_pvt *p)
2978 {
2979         int res;
2980         ZT_SPANINFO zi;
2981         memset(&zi, 0, sizeof(zi));
2982         zi.spanno = p->span;
2983         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2984         if (res < 0) {
2985                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2986                 return 0;
2987         }
2988         return zi.alarms;
2989 }
2990                         
2991 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2992 {
2993         int res,x;
2994         int index;
2995         char *c;