024596e17300eb3e5a516895293e8a1cc69ca449
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Zaptel Pseudo TDM interface 
5  * 
6  * Copyright (C) 2003 Digium
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <string.h>
16 #include <asterisk/lock.h>
17 #include <asterisk/channel.h>
18 #include <asterisk/channel_pvt.h>
19 #include <asterisk/config.h>
20 #include <asterisk/logger.h>
21 #include <asterisk/module.h>
22 #include <asterisk/pbx.h>
23 #include <asterisk/options.h>
24 #include <asterisk/file.h>
25 #include <asterisk/ulaw.h>
26 #include <asterisk/alaw.h>
27 #include <asterisk/callerid.h>
28 #include <asterisk/adsi.h>
29 #include <asterisk/cli.h>
30 #include <asterisk/cdr.h>
31 #include <asterisk/features.h>
32 #include <asterisk/musiconhold.h>
33 #include <asterisk/say.h>
34 #include <asterisk/tdd.h>
35 #include <asterisk/app.h>
36 #include <asterisk/dsp.h>
37 #include <asterisk/astdb.h>
38 #include <asterisk/manager.h>
39 #include <asterisk/causes.h>
40 #include <asterisk/term.h>
41 #include <asterisk/utils.h>
42 #include <sys/signal.h>
43 #include <errno.h>
44 #include <stdlib.h>
45 #include <stdint.h>
46 #include <unistd.h>
47 #include <sys/ioctl.h>
48 #ifdef __linux__
49 #include <linux/zaptel.h>
50 #else
51 #include <zaptel.h>
52 #endif /* __linux__ */
53 #include <math.h>
54 #include <tonezone.h>
55 #include <ctype.h>
56 #ifdef ZAPATA_PRI
57 #include <libpri.h>
58 #ifndef PRI_NSF_NONE
59 #error "You need newer libpri"
60 #endif
61 #endif
62 #ifdef ZAPATA_R2
63 #include <libmfcr2.h>
64 #endif
65
66 #include "../asterisk.h"
67
68 #ifndef ZT_SIG_EM_E1
69 #error "Your zaptel is too old.  please cvs update"
70 #endif
71
72 /*
73  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
74  * the user hangs up to reset the state machine so ring works properly.
75  * This is used to be able to support kewlstart by putting the zhone in
76  * groundstart mode since their forward disconnect supervision is entirely
77  * broken even though their documentation says it isn't and their support
78  * is entirely unwilling to provide any assistance with their channel banks
79  * even though their web site says they support their products for life.
80  */
81
82 /* #define ZHONE_HACK */
83
84 /* Typically, how many rings before we should send Caller*ID */
85 #define DEFAULT_CIDRINGS 1
86
87 #define CHANNEL_PSEUDO -12
88
89 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
90
91 static char *desc = "Zapata Telephony"
92 #ifdef ZAPATA_PRI
93                " w/PRI"
94 #endif
95 #ifdef ZAPATA_R2
96                " w/R2"
97 #endif
98 ;
99
100 static char *tdesc = "Zapata Telephony Driver"
101 #ifdef ZAPATA_PRI
102                " w/PRI"
103 #endif
104 #ifdef ZAPATA_R2
105                " w/R2"
106 #endif
107 ;
108
109 static char *type = "Zap";
110 static char *typecompat = "Tor";        /* Retain compatibility with chan_tor */
111 static char *config = "zapata.conf";
112
113 #define SIG_EM          ZT_SIG_EM
114 #define SIG_EMWINK      (0x100000 | ZT_SIG_EM)
115 #define SIG_FEATD       (0x200000 | ZT_SIG_EM)
116 #define SIG_FEATDMF     (0x400000 | ZT_SIG_EM)
117 #define SIG_FEATB       (0x800000 | ZT_SIG_EM)
118 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
119 #define SIG_FXSLS       ZT_SIG_FXSLS
120 #define SIG_FXSGS       ZT_SIG_FXSGS
121 #define SIG_FXSKS       ZT_SIG_FXSKS
122 #define SIG_FXOLS       ZT_SIG_FXOLS
123 #define SIG_FXOGS       ZT_SIG_FXOGS
124 #define SIG_FXOKS       ZT_SIG_FXOKS
125 #define SIG_PRI         ZT_SIG_CLEAR
126 #define SIG_R2          ZT_SIG_CAS
127 #define SIG_SF          ZT_SIG_SF
128 #define SIG_SFWINK      (0x100000 | ZT_SIG_SF)
129 #define SIG_SF_FEATD    (0x200000 | ZT_SIG_SF)
130 #define SIG_SF_FEATDMF  (0x400000 | ZT_SIG_SF)
131 #define SIG_SF_FEATB    (0x800000 | ZT_SIG_SF)
132 #define SIG_EM_E1       ZT_SIG_EM_E1
133 #define SIG_GR303FXOKS   (0x100000 | ZT_SIG_FXOKS)
134 #define SIG_GR303FXSKS   (0x200000 | ZT_SIG_FXSKS)
135
136 #define NUM_SPANS       32
137 #define NUM_DCHANS      4               /* No more than 4 d-channels */
138 #define MAX_CHANNELS    672     /* No more than a DS3 per trunk group */
139 #define RESET_INTERVAL  3600    /* How often (in seconds) to reset unused channels */
140
141 #define CHAN_PSEUDO     -2
142
143 #define DCHAN_PROVISIONED (1 << 0)
144 #define DCHAN_NOTINALARM  (1 << 1)
145 #define DCHAN_UP          (1 << 2)
146
147 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
148
149 static char context[AST_MAX_EXTENSION] = "default";
150 static char callerid[256] = "";
151
152 static char language[MAX_LANGUAGE] = "";
153 static char musicclass[MAX_LANGUAGE] = "";
154 static char progzone[10]= "";
155
156 static int usedistinctiveringdetection = 0;
157
158 static int use_callerid = 1;
159 static int zaptrcallerid = 0;
160 static int cur_signalling = -1;
161
162 static unsigned int cur_group = 0;
163 static unsigned int cur_callergroup = 0;
164 static unsigned int cur_pickupgroup = 0;
165 static int relaxdtmf = 0;
166
167 static int immediate = 0;
168
169 static int stripmsd = 0;
170
171 static int callwaiting = 0;
172
173 static int callwaitingcallerid = 0;
174
175 static int hidecallerid = 0;
176
177 static int restrictcid = 0;
178
179 static int use_callingpres = 0;
180
181 static int callreturn = 0;
182
183 static int threewaycalling = 0;
184
185 static int transfer = 0;
186
187 static int cancallforward = 0;
188
189 static float rxgain = 0.0;
190
191 static float txgain = 0.0;
192
193 static int tonezone = -1;
194
195 static int echocancel;
196
197 static int echotraining;
198
199 static int echocanbridged = 0;
200
201 static int busydetect = 0;
202
203 static int busycount = 3;
204
205 static int callprogress = 0;
206
207 static char accountcode[20] = "";
208
209 static char mailbox[AST_MAX_EXTENSION];
210
211 static int amaflags = 0;
212
213 static int adsi = 0;
214
215 static int numbufs = 4;
216
217 static int cur_prewink = -1;
218 static int cur_preflash = -1;
219 static int cur_wink = -1;
220 static int cur_flash = -1;
221 static int cur_start = -1;
222 static int cur_rxwink = -1;
223 static int cur_rxflash = -1;
224 static int cur_debounce = -1;
225
226 #ifdef ZAPATA_PRI
227 static int minunused = 2;
228 static int minidle = 0;
229 static char idleext[AST_MAX_EXTENSION];
230 static char idledial[AST_MAX_EXTENSION];
231 static int overlapdial = 0;
232 static struct ast_channel inuse = { "GR-303InUse" };
233 #endif
234
235 /* Wait up to 16 seconds for first digit (FXO logic) */
236 static int firstdigittimeout = 16000;
237
238 /* How long to wait for following digits (FXO logic) */
239 static int gendigittimeout = 8000;
240
241 /* How long to wait for an extra digit, if there is an ambiguous match */
242 static int matchdigittimeout = 3000;
243
244 static int usecnt =0;
245 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
246
247 /* Protect the interface list (of zt_pvt's) */
248 AST_MUTEX_DEFINE_STATIC(iflock);
249
250 static int ifcount = 0;
251
252 /* Protect the monitoring thread, so only one process can kill or start it, and not
253    when it's doing something critical. */
254 AST_MUTEX_DEFINE_STATIC(monlock);
255
256 /* This is the thread for the monitor which checks for input on the channels
257    which are not currently in use.  */
258 static pthread_t monitor_thread = AST_PTHREADT_NULL;
259
260 static int restart_monitor(void);
261
262 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
263
264 static int zt_sendtext(struct ast_channel *c, char *text);
265
266 static inline int zt_get_event(int fd)
267 {
268         /* Avoid the silly zt_getevent which ignores a bunch of events */
269         int j;
270         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
271         return j;
272 }
273
274 static inline int zt_wait_event(int fd)
275 {
276         /* Avoid the silly zt_waitevent which ignores a bunch of events */
277         int i,j=0;
278         i = ZT_IOMUX_SIGEVENT;
279         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
280         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
281         return j;
282 }
283
284 /* Chunk size to read -- we use 20ms chunks to make things happy.  */   
285 #define READ_SIZE 160
286
287 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
288 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
289
290 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
291 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
292 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /* 500 ms */
293 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /* 2000 ms */
294 #define RINGT                                           ( (8000 * 8) / READ_SIZE)
295
296 struct zt_pvt;
297
298
299 #ifdef ZAPATA_R2
300 static int r2prot = -1;
301 #endif
302
303
304 #ifdef ZAPATA_PRI
305
306 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8))
307 #define PRI_CHANNEL(p) ((p) & 0xff)
308 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
309
310 struct zt_pri {
311         pthread_t master;                       /* Thread of master */
312         ast_mutex_t lock;               /* Mutex */
313         char idleext[AST_MAX_EXTENSION];                /* Where to idle extra calls */
314         char idlecontext[AST_MAX_EXTENSION];            /* What context to use for idle */
315         char idledial[AST_MAX_EXTENSION];               /* What to dial before dumping */
316         int minunused;                          /* Min # of channels to keep empty */
317         int minidle;                            /* Min # of "idling" calls to keep active */
318         int nodetype;                           /* Node type */
319         int switchtype;                         /* Type of switch to emulate */
320         int nsf;                        /* Network-Specific Facilities */
321         int dialplan;                   /* Dialing plan */
322         int localdialplan;              /* Local dialing plan */
323         int dchannels[NUM_DCHANS];      /* What channel are the dchannels on */
324         int trunkgroup;                 /* What our trunkgroup is */
325         int mastertrunkgroup;   /* What trunk group is our master */
326         int prilogicalspan;             /* Logical span number within trunk group */
327         int numchans;                   /* Num of channels we represent */
328         int overlapdial;                /* In overlap dialing mode */
329         struct pri *dchans[NUM_DCHANS]; /* Actual d-channels */
330         int dchanavail[NUM_DCHANS];             /* Whether each channel is available */
331         struct pri *pri;                                /* Currently active D-channel */
332         int debug;
333         int fds[NUM_DCHANS];    /* FD's for d-channels */
334         int offset;
335         int span;
336         int resetting;
337         int resetpos;
338         time_t lastreset;
339         struct zt_pvt *pvts[MAX_CHANNELS];      /* Member channel pvt structs */
340         struct zt_pvt *crvs;                            /* Member CRV structs */
341         struct zt_pvt *crvend;                          /* Pointer to end of CRV structs */
342 };
343
344
345 static struct zt_pri pris[NUM_SPANS];
346
347 static int pritype = PRI_CPE;
348
349 #if 0
350 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
351 #else
352 #define DEFAULT_PRI_DEBUG 0
353 #endif
354
355 static inline void pri_rel(struct zt_pri *pri)
356 {
357         ast_mutex_unlock(&pri->lock);
358 }
359
360 static int switchtype = PRI_SWITCH_NI2;
361 static int nsf = PRI_NSF_NONE;
362 static int dialplan = PRI_NATIONAL_ISDN + 1;
363 static int localdialplan = PRI_NATIONAL_ISDN + 1;
364
365 #else
366 /* Shut up the compiler */
367 struct zt_pri;
368 #endif
369
370 #define SUB_REAL                0                       /* Active call */
371 #define SUB_CALLWAIT    1                       /* Call-Waiting call on hold */
372 #define SUB_THREEWAY    2                       /* Three-way call */
373
374
375 static struct zt_distRings drings;
376
377 struct distRingData {
378         int ring[3];
379 };
380 struct ringContextData {
381         char contextData[AST_MAX_EXTENSION];
382 };
383 struct zt_distRings {
384         struct distRingData ringnum[3];
385         struct ringContextData ringContext[3];
386 };
387
388 static char *subnames[] = {
389         "Real",
390         "Callwait",
391         "Threeway"
392 };
393
394 struct zt_subchannel {
395         int zfd;
396         struct ast_channel *owner;
397         int chan;
398         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
399         struct ast_frame f;             /* One frame for each channel.  How did this ever work before? */
400         int needringing;
401         int needbusy;
402         int needcongestion;
403         int needcallerid;
404         int needanswer;
405         int linear;
406         int inthreeway;
407         ZT_CONFINFO curconf;
408 };
409
410 #define CONF_USER_REAL          (1 << 0)
411 #define CONF_USER_THIRDCALL     (1 << 1)
412
413 #define MAX_SLAVES      4
414
415 static struct zt_pvt {
416         ast_mutex_t lock;
417         struct ast_channel *owner;      /* Our current active owner (if applicable) */
418                 /* Up to three channels can be associated with this call */
419                 
420         struct zt_subchannel sub_unused;        /* Just a safety precaution */
421         struct zt_subchannel subs[3];   /* Sub-channels */
422         struct zt_confinfo saveconf;    /* Saved conference info */
423
424         struct zt_pvt *slaves[MAX_SLAVES];      /* Slave to us (follows our conferencing) */
425         struct zt_pvt *master;  /* Master to us (we follow their conferencing) */
426         int inconference;               /* If our real should be in the conference */
427         
428         int sig;                                        /* Signalling style */
429         int radio;                              /* radio type */
430         int firstradio;                         /* first radio flag */
431         float rxgain;
432         float txgain;
433         int tonezone;                           /* tone zone for this chan, or -1 for default */
434         struct zt_pvt *next;                    /* Next channel in list */
435         struct zt_pvt *prev;                    /* Prev channel in list */
436
437         struct zt_distRings drings;
438         int usedistinctiveringdetection;
439
440         char context[AST_MAX_EXTENSION];
441         char defcontext[AST_MAX_EXTENSION];
442         char exten[AST_MAX_EXTENSION];
443         char language[MAX_LANGUAGE];
444         char musicclass[MAX_LANGUAGE];
445         char callerid[AST_MAX_EXTENSION];
446         char lastcallerid[AST_MAX_EXTENSION];
447         char *origcallerid;                     /* malloced original callerid */
448         char callwaitcid[AST_MAX_EXTENSION];
449         char rdnis[AST_MAX_EXTENSION];
450         char dnid[AST_MAX_EXTENSION];
451         unsigned int group;
452         int law;
453         int confno;                                     /* Our conference */
454         int confusers;                          /* Who is using our conference */
455         int propconfno;                         /* Propagated conference number */
456         unsigned int callgroup;
457         unsigned int pickupgroup;
458         int immediate;                          /* Answer before getting digits? */
459         int channel;                            /* Channel Number or CRV */
460         int span;                                       /* Span number */
461         int dialing;
462         time_t guardtime;                       /* Must wait this much time before using for new call */
463         int dialednone;
464         int use_callerid;                       /* Whether or not to use caller id on this channel */
465         int hidecallerid;
466         int callreturn;
467         int permhidecallerid;           /* Whether to hide our outgoing caller ID or not */
468         int restrictcid;                /* Whether restrict the callerid -> only send ANI */
469         int use_callingpres;            /* Whether to use the callingpres the calling switch sends */
470         int callingpres;                /* The value of callling presentation that we're going to use when placing a PRI call */
471         int callwaitingrepeat;          /* How many samples to wait before repeating call waiting */
472         int cidcwexpire;                        /* When to expire our muting for CID/CW */
473         unsigned char *cidspill;
474         int cidpos;
475         int cidlen;
476         int ringt;
477         int stripmsd;
478         int callwaiting;
479         int callwaitcas;
480         int callwaitrings;
481         int echocancel;
482         int echotraining;
483         int echocanbridged;
484         int echocanon;
485         int echobreak;
486         char echorest[20];
487         int permcallwaiting;
488         int callwaitingcallerid;
489         int threewaycalling;
490         int transfer;
491         int digital;
492         int outgoing;
493         int dnd;
494         int busydetect;
495         int busycount;
496         int callprogress;
497         struct timeval flashtime;       /* Last flash-hook time */
498         struct ast_dsp *dsp;
499         int cref;                                       /* Call reference number */
500         ZT_DIAL_OPERATION dop;
501         int destroy;
502         int ignoredtmf;                         
503         int inalarm;
504         char accountcode[20];           /* Account code */
505         int amaflags;                           /* AMA Flags */
506         char didtdd;                    /* flag to say its done it once */
507         struct tdd_state *tdd;          /* TDD flag */
508         int adsi;
509         int cancallforward;
510         char call_forward[AST_MAX_EXTENSION];
511         char mailbox[AST_MAX_EXTENSION];
512         char dialdest[256];
513         int onhooktime;
514         int msgstate;
515         
516         int confirmanswer;              /* Wait for '#' to confirm answer */
517         int distinctivering;    /* Which distinctivering to use */
518         int cidrings;                   /* Which ring to deliver CID on */
519         
520         int faxhandled;                 /* Has a fax tone already been handled? */
521         
522         char mate;                      /* flag to say its in MATE mode */
523         int pulsedial;          /* whether a pulse dial phone is detected */
524         int dtmfrelax;          /* whether to run in relaxed DTMF mode */
525         int fake_event;
526         int zaptrcallerid;      /* should we use the callerid from incoming call on zap transfer or not */
527 #ifdef ZAPATA_PRI
528         struct zt_pri *pri;
529         struct zt_pvt *bearer;
530         struct zt_pvt *realcall;
531         q931_call *call;
532         int isidlecall;
533         int resetting;
534         int prioffset;
535         int logicalspan;
536         int alreadyhungup;
537         int proceeding;
538         int setup_ack;          /* wheter we received SETUP_ACKNOWLEDGE or not */
539 #endif  
540 #ifdef ZAPATA_R2
541         int r2prot;
542         mfcr2_t *r2;
543         int hasr2call;
544         int r2blocked;
545         int sigchecked;
546 #endif  
547 } *iflist = NULL, *ifend = NULL;
548
549 #ifdef ZAPATA_PRI
550 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
551 #else
552 #define GET_CHANNEL(p) ((p)->channel)
553 #endif
554
555 struct zt_pvt *round_robin[32];
556
557 #ifdef ZAPATA_PRI
558 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
559 {
560         int res;
561         /* Grab the lock first */
562         do {
563             res = ast_mutex_trylock(&pri->lock);
564                 if (res) {
565                         ast_mutex_unlock(&pvt->lock);
566                         /* Release the lock and try again */
567                         usleep(1);
568                         ast_mutex_lock(&pvt->lock);
569                 }
570         } while(res);
571         /* Then break the poll */
572         pthread_kill(pri->master, SIGURG);
573         return 0;
574 }
575 #endif
576
577 #define NUM_CADENCE_MAX 25
578 static int num_cadence = 4;
579 static int user_has_defined_cadences = 0;
580
581 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
582         { { 125, 125, 2000, 4000 } },                   /* Quick chirp followed by normal ring */
583         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /* British style ring */
584         { { 125, 125, 125, 125, 125, 4000 } },  /* Three short bursts */
585         { { 1000, 500, 2500, 5000 } },  /* Long ring */
586 };
587
588 int receivedRingT; /* Used to find out what ringtone we are on */
589
590 /* cidrings says in which pause to transmit the cid information, where the first pause
591  * is 1, the second pause is 2 and so on.
592  */
593
594 static int cidrings[NUM_CADENCE_MAX] = {
595         2,                                                                              /* Right after first long ring */
596         4,                                                                              /* Right after long part */
597         3,                                                                              /* After third chirp */
598         2,                                                                              /* Second spell */
599 };
600
601 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
602                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
603
604 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
605 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
606
607 #ifdef ZAPATA_PRI
608 /* translate between PRI causes and asterisk's */
609 static int hangup_pri2cause(int cause)
610 {
611         switch(cause) {
612                 case PRI_CAUSE_USER_BUSY:
613                         return AST_CAUSE_BUSY;
614                 case PRI_CAUSE_NORMAL_CLEARING:
615                         return AST_CAUSE_NORMAL;
616                 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
617                 case PRI_CAUSE_REQUESTED_CHAN_UNAVAIL:
618                         return AST_CAUSE_CONGESTION;
619                 case PRI_CAUSE_UNALLOCATED:
620                 case PRI_CAUSE_NUMBER_CHANGED:
621                         return AST_CAUSE_UNALLOCATED;
622                 case PRI_CAUSE_NO_USER_RESPONSE:
623                 case PRI_CAUSE_NO_ANSWER:
624                         return AST_CAUSE_NOANSWER;
625                 default:
626                         return AST_CAUSE_FAILURE;
627         }
628         /* never reached */
629         return 0;
630 }
631
632 /* translate between ast cause and PRI */
633 static int hangup_cause2pri(int cause)
634 {
635         switch(cause) {
636                 case AST_CAUSE_BUSY:
637                         return PRI_CAUSE_USER_BUSY;
638                 case AST_CAUSE_UNALLOCATED:
639                         return PRI_CAUSE_UNALLOCATED;
640                 case AST_CAUSE_CONGESTION:
641                         return PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION;
642                 case AST_CAUSE_NORMAL:
643                 default:
644                         return PRI_CAUSE_NORMAL_CLEARING;
645         }
646         /* never reached */
647         return 0;
648 }
649 #endif
650
651 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
652 {
653         int res;
654         if (p->subs[0].owner == ast)
655                 res = 0;
656         else if (p->subs[1].owner == ast)
657                 res = 1;
658         else if (p->subs[2].owner == ast)
659                 res = 2;
660         else {
661                 res = -1;
662                 if (!nullok)
663                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
664         }
665         return res;
666 }
667
668 static void wakeup_sub(struct zt_pvt *p, int a)
669 {
670         struct ast_frame null = { AST_FRAME_NULL, };
671         for (;;) {
672                 if (p->subs[a].owner) {
673                         if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
674                                 ast_mutex_unlock(&p->lock);
675                                 usleep(1);
676                                 ast_mutex_lock(&p->lock);
677                         } else {
678                                 ast_queue_frame(p->subs[a].owner, &null);
679                                 ast_mutex_unlock(&p->subs[a].owner->lock);
680                                 break;
681                         }
682                 } else
683                         break;
684         }
685 }
686
687 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f)
688 {
689         for (;;) {
690                 if (p->owner) {
691                         if (ast_mutex_trylock(&p->owner->lock)) {
692                                 ast_mutex_unlock(&p->lock);
693                                 usleep(1);
694                                 ast_mutex_lock(&p->lock);
695                         } else {
696                                 ast_queue_frame(p->owner, f);
697                                 ast_mutex_unlock(&p->owner->lock);
698                                 break;
699                         }
700                 } else
701                         break;
702         }
703 }
704
705 static void swap_subs(struct zt_pvt *p, int a, int b)
706 {
707         int tchan;
708         int tinthreeway;
709         struct ast_channel *towner;
710
711         ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
712
713         tchan = p->subs[a].chan;
714         towner = p->subs[a].owner;
715         tinthreeway = p->subs[a].inthreeway;
716
717         p->subs[a].chan = p->subs[b].chan;
718         p->subs[a].owner = p->subs[b].owner;
719         p->subs[a].inthreeway = p->subs[b].inthreeway;
720
721         p->subs[b].chan = tchan;
722         p->subs[b].owner = towner;
723         p->subs[b].inthreeway = tinthreeway;
724
725         if (p->subs[a].owner) 
726                 p->subs[a].owner->fds[0] = p->subs[a].zfd;
727         if (p->subs[b].owner) 
728                 p->subs[b].owner->fds[0] = p->subs[b].zfd;
729         wakeup_sub(p, a);
730         wakeup_sub(p, b);
731 }
732
733 static int zt_open(char *fn)
734 {
735         int fd;
736         int isnum;
737         int chan = 0;
738         int bs;
739         int x;
740         isnum = 1;
741         for (x=0;x<strlen(fn);x++) {
742                 if (!isdigit(fn[x])) {
743                         isnum = 0;
744                         break;
745                 }
746         }
747         if (isnum) {
748                 chan = atoi(fn);
749                 if (chan < 1) {
750                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
751                         return -1;
752                 }
753                 fn = "/dev/zap/channel";
754         }
755         fd = open(fn, O_RDWR | O_NONBLOCK);
756         if (fd < 0) {
757                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
758                 return -1;
759         }
760         if (chan) {
761                 if (ioctl(fd, ZT_SPECIFY, &chan)) {
762                         x = errno;
763                         close(fd);
764                         errno = x;
765                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
766                         return -1;
767                 }
768         }
769         bs = READ_SIZE;
770         if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
771         return fd;
772 }
773
774 static void zt_close(int fd)
775 {
776         close(fd);
777 }
778
779 int zt_setlinear(int zfd, int linear)
780 {
781         int res;
782         res = ioctl(zfd, ZT_SETLINEAR, &linear);
783         if (res)
784                 return res;
785         return 0;
786 }
787
788
789 int zt_setlaw(int zfd, int law)
790 {
791         int res;
792         res = ioctl(zfd, ZT_SETLAW, &law);
793         if (res)
794                 return res;
795         return 0;
796 }
797
798 static int alloc_sub(struct zt_pvt *p, int x)
799 {
800         ZT_BUFFERINFO bi;
801         int res;
802         if (p->subs[x].zfd < 0) {
803                 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
804                 if (p->subs[x].zfd > -1) {
805                         res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
806                         if (!res) {
807                                 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
808                                 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
809                                 bi.numbufs = numbufs;
810                                 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
811                                 if (res < 0) {
812                                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
813                                 }
814                         } else 
815                                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
816                         if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
817                                 ast_log(LOG_WARNING,"Unable to get channel number for pseudo channel on FD %d\n",p->subs[x].zfd);
818                                 zt_close(p->subs[x].zfd);
819                                 p->subs[x].zfd = -1;
820                                 return -1;
821                         }
822                         if (option_debug)
823                                 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
824                         return 0;
825                 } else
826                         ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
827                 return -1;
828         }
829         ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
830         return -1;
831 }
832
833 static int unalloc_sub(struct zt_pvt *p, int x)
834 {
835         if (!x) {
836                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
837                 return -1;
838         }
839         ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
840         if (p->subs[x].zfd > -1) {
841                 zt_close(p->subs[x].zfd);
842         }
843         p->subs[x].zfd = -1;
844         p->subs[x].linear = 0;
845         p->subs[x].chan = 0;
846         p->subs[x].owner = NULL;
847         p->subs[x].inthreeway = 0;
848         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
849         return 0;
850 }
851
852 static int zt_digit(struct ast_channel *ast, char digit)
853 {
854         ZT_DIAL_OPERATION zo;
855         struct zt_pvt *p;
856         int res = 0;
857         int index;
858         p = ast->pvt->pvt;
859         ast_mutex_lock(&p->lock);
860         index = zt_get_index(ast, p, 0);
861         if (index == SUB_REAL) {
862 #ifdef ZAPATA_PRI
863                 if (p->sig == SIG_PRI && ast->_state == AST_STATE_DIALING && (p->proceeding < 2)) {
864                         if (p->setup_ack) {
865                                 if (!pri_grab(p, p->pri)) {
866                                         pri_information(p->pri->pri,p->call,digit);
867                                         pri_rel(p->pri);
868                                 } else
869                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
870                         } else if (strlen(p->dialdest) < sizeof(p->dialdest) - 1) {
871                                 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
872                                 res = strlen(p->dialdest);
873                                 p->dialdest[res++] = digit;
874                                 p->dialdest[res] = '\0';
875                         }
876                 } else {
877 #else
878                 {
879 #endif
880                         zo.op = ZT_DIAL_OP_APPEND;
881                         zo.dialstr[0] = 'T';
882                         zo.dialstr[1] = digit;
883                         zo.dialstr[2] = 0;
884                         if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
885                                 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
886                         else
887                                 p->dialing = 1;
888                 }
889         }
890         ast_mutex_unlock(&p->lock);
891         return res;
892 }
893
894 static char *events[] = {
895         "No event",
896         "On hook",
897         "Ring/Answered",
898         "Wink/Flash",
899         "Alarm",
900         "No more alarm",
901                 "HDLC Abort",
902                 "HDLC Overrun",
903                 "HDLC Bad FCS",
904                 "Dial Complete",
905                 "Ringer On",
906                 "Ringer Off",
907                 "Hook Transition Complete",
908                 "Bits Changed",
909                 "Pulse Start"
910 };
911
912 static struct {
913         int alarm;
914         char *name;
915 } alarms[] = {
916         { ZT_ALARM_RED, "Red Alarm" },
917         { ZT_ALARM_YELLOW, "Yellow Alarm" },
918         { ZT_ALARM_BLUE, "Blue Alarm" },
919         { ZT_ALARM_RECOVER, "Recovering" },
920         { ZT_ALARM_LOOPBACK, "Loopback" },
921         { ZT_ALARM_NOTOPEN, "Not Open" },
922         { ZT_ALARM_NONE, "None" },
923 };
924
925 static char *alarm2str(int alarm)
926 {
927         int x;
928         for (x=0;x<sizeof(alarms) / sizeof(alarms[0]); x++) {
929                 if (alarms[x].alarm & alarm)
930                         return alarms[x].name;
931         }
932         return alarm ? "Unknown Alarm" : "No Alarm";
933 }
934
935 static char *event2str(int event)
936 {
937         static char buf[256];
938         if ((event < 15) && (event > -1))
939                 return events[event];
940         sprintf(buf, "Event %d", event); /* safe */
941         return buf;
942 }
943
944 #ifdef ZAPATA_R2
945 static int str2r2prot(char *swtype)
946 {
947     if (!strcasecmp(swtype, "ar"))
948         return MFCR2_PROT_ARGENTINA;
949     /*endif*/
950     if (!strcasecmp(swtype, "cn"))
951         return MFCR2_PROT_CHINA;
952     /*endif*/
953     if (!strcasecmp(swtype, "kr"))
954         return MFCR2_PROT_KOREA;
955     /*endif*/
956     return -1;
957 }
958 #endif
959
960 static char *sig2str(int sig)
961 {
962         static char buf[256];
963         switch(sig) {
964         case SIG_EM:
965                 return "E & M Immediate";
966         case SIG_EMWINK:
967                 return "E & M Wink";
968         case SIG_EM_E1:
969                 return "E & M E1";
970         case SIG_FEATD:
971                 return "Feature Group D (DTMF)";
972         case SIG_FEATDMF:
973                 return "Feature Group D (MF)";
974         case SIG_FEATB:
975                 return "Feature Group B (MF)";
976         case SIG_E911:
977                 return "E911 (MF)";
978         case SIG_FXSLS:
979                 return "FXS Loopstart";
980         case SIG_FXSGS:
981                 return "FXS Groundstart";
982         case SIG_FXSKS:
983                 return "FXS Kewlstart";
984         case SIG_FXOLS:
985                 return "FXO Loopstart";
986         case SIG_FXOGS:
987                 return "FXO Groundstart";
988         case SIG_FXOKS:
989                 return "FXO Kewlstart";
990         case SIG_PRI:
991                 return "PRI Signalling";
992         case SIG_R2:
993                 return "R2 Signalling";
994         case SIG_SF:
995                 return "SF (Tone) Signalling Immediate";
996         case SIG_SFWINK:
997                 return "SF (Tone) Signalling Wink";
998         case SIG_SF_FEATD:
999                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1000         case SIG_SF_FEATDMF:
1001                 return "SF (Tone) Signalling with Feature Group D (MF)";
1002         case SIG_SF_FEATB:
1003                 return "SF (Tone) Signalling with Feature Group B (MF)";
1004         case SIG_GR303FXOKS:
1005                 return "GR-303 Signalling with FXOKS";
1006         case SIG_GR303FXSKS:
1007                 return "GR-303 Signalling with FXSKS";
1008         case 0:
1009                 return "Pseudo Signalling";
1010         default:
1011                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1012                 return buf;
1013         }
1014 }
1015
1016 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1017 {
1018         /* If the conference already exists, and we're already in it
1019            don't bother doing anything */
1020         ZT_CONFINFO zi;
1021         
1022         memset(&zi, 0, sizeof(zi));
1023         zi.chan = 0;
1024
1025         if (slavechannel > 0) {
1026                 /* If we have only one slave, do a digital mon */
1027                 zi.confmode = ZT_CONF_DIGITALMON;
1028                 zi.confno = slavechannel;
1029         } else {
1030                 if (!index) {
1031                         /* Real-side and pseudo-side both participate in conference */
1032                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1033                                                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1034                 } else
1035                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1036                 zi.confno = p->confno;
1037         }
1038         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1039                 return 0;
1040         if (c->zfd < 0)
1041                 return 0;
1042         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1043                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1044                 return -1;
1045         }
1046         if (slavechannel < 1) {
1047                 p->confno = zi.confno;
1048         }
1049         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1050         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1051         return 0;
1052 }
1053
1054 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1055 {
1056         /* If they're listening to our channel, they're ours */ 
1057         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1058                 return 1;
1059         /* If they're a talker on our (allocated) conference, they're ours */
1060         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1061                 return 1;
1062         return 0;
1063 }
1064
1065 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1066 {
1067         ZT_CONFINFO zi;
1068         if (/* Can't delete if there's no zfd */
1069                 (c->zfd < 0) ||
1070                 /* Don't delete from the conference if it's not our conference */
1071                 !isourconf(p, c)
1072                 /* Don't delete if we don't think it's conferenced at all (implied) */
1073                 ) return 0;
1074         memset(&zi, 0, sizeof(zi));
1075         zi.chan = 0;
1076         zi.confno = 0;
1077         zi.confmode = 0;
1078         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1079                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1080                 return -1;
1081         }
1082         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1083         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1084         return 0;
1085 }
1086
1087 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1088 {
1089         int x;
1090         int useslavenative;
1091         struct zt_pvt *slave = NULL;
1092         /* Start out optimistic */
1093         useslavenative = 1;
1094         /* Update conference state in a stateless fashion */
1095         for (x=0;x<3;x++) {
1096                 /* Any three-way calling makes slave native mode *definitely* out
1097                    of the question */
1098                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1099                         useslavenative = 0;
1100         }
1101         /* If we don't have any 3-way calls, check to see if we have
1102            precisely one slave */
1103         if (useslavenative) {
1104                 for (x=0;x<MAX_SLAVES;x++) {
1105                         if (p->slaves[x]) {
1106                                 if (slave) {
1107                                         /* Whoops already have a slave!  No 
1108                                            slave native and stop right away */
1109                                         slave = NULL;
1110                                         useslavenative = 0;
1111                                         break;
1112                                 } else {
1113                                         /* We have one slave so far */
1114                                         slave = p->slaves[x];
1115                                 }
1116                         }
1117                 }
1118         }
1119         /* If no slave, slave native definitely out */
1120         if (!slave)
1121                 useslavenative = 0;
1122         else if (slave->law != p->law) {
1123                 useslavenative = 0;
1124                 slave = NULL;
1125         }
1126         if (out)
1127                 *out = slave;
1128         return useslavenative;
1129 }
1130
1131 static int 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                 /* Start the trunk, if not GR-303 */
1614                 if (!p->pri) {
1615                         x = ZT_START;
1616                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1617                         if (res < 0) {
1618                                 if (errno != EINPROGRESS) {
1619                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1620                                         ast_mutex_unlock(&p->lock);
1621                                         return -1;
1622                                 }
1623                         }
1624                 }
1625                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1626                 p->dop.op = ZT_DIAL_OP_REPLACE;
1627                 if (p->sig == SIG_FEATD) {
1628                         if (ast->callerid) {
1629                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1630                                 ast_callerid_parse(callerid, &n, &l);
1631                                 if (l) {
1632                                         ast_shrink_phone_number(l);
1633                                         if (!ast_isphonenumber(l))
1634                                                 l = NULL;
1635                                 }
1636                         } else
1637                                 l = NULL;
1638                         if (l) 
1639                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1640                         else
1641                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1642                 } else 
1643                 if (p->sig == SIG_FEATDMF) {
1644                         if (ast->callerid) {
1645                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1646                                 ast_callerid_parse(callerid, &n, &l);
1647                                 if (l) {
1648                                         ast_shrink_phone_number(l);
1649                                         if (!ast_isphonenumber(l))
1650                                                 l = NULL;
1651                                 }
1652                         } else
1653                                 l = NULL;
1654                         if (l) 
1655                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1656                         else
1657                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1658                 } else 
1659                 if (p->sig == SIG_E911) {
1660                         strncpy(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr) - 1);
1661                 } else
1662                 if (p->sig == SIG_FEATB) {
1663                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1664                 } else 
1665                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c + p->stripmsd);
1666                 if (strlen(p->dop.dialstr) > 4) {
1667                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1668                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1669                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1670                         p->echobreak = 1;
1671                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1672                 } else
1673                         p->echobreak = 0;
1674                 if (!res) {
1675                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1676                                 x = ZT_ONHOOK;
1677                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1678                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1679                                 ast_mutex_unlock(&p->lock);
1680                                 return -1;
1681                         }
1682                 } else
1683                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1684                 p->dialing = 1;
1685                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1686                 ast_setstate(ast, AST_STATE_DIALING);
1687                 break;
1688         case 0:
1689                 /* Special pseudo -- automatically up*/
1690                 ast_setstate(ast, AST_STATE_UP);
1691                 break;          
1692         case SIG_PRI:
1693                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1694                 p->dialdest[0] = '\0';
1695                 break;
1696         default:
1697                 ast_log(LOG_DEBUG, "not yet implemented\n");
1698                 ast_mutex_unlock(&p->lock);
1699                 return -1;
1700         }
1701 #ifdef ZAPATA_PRI
1702         if (p->pri) {
1703                 struct pri_sr *sr;
1704                 c = strchr(dest, '/');
1705                 if (c)
1706                         c++;
1707                 else
1708                         c = dest;
1709                 if (ast->callerid && !p->hidecallerid) {
1710                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1711                         ast_callerid_parse(callerid, &n, &l);
1712                         if (l) {
1713                                 ast_shrink_phone_number(l);
1714                                 if (!ast_isphonenumber(l))
1715                                         l = NULL;
1716                         }
1717                 } else
1718                         l = NULL;
1719                 if (strlen(c) < p->stripmsd) {
1720                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1721                         ast_mutex_unlock(&p->lock);
1722                         return -1;
1723                 }
1724                 if (p->sig != SIG_FXSKS) {
1725                         p->dop.op = ZT_DIAL_OP_REPLACE;
1726                         s = strchr(c + p->stripmsd, 'w');
1727                         if (s) {
1728                                 if (strlen(s))
1729                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1730                                 else
1731                                         p->dop.dialstr[0] = '\0';
1732                                 *s = '\0';
1733                         } else {
1734                                 p->dop.dialstr[0] = '\0';
1735                         }
1736                 }
1737                 if (pri_grab(p, p->pri)) {
1738                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1739                         ast_mutex_unlock(&p->lock);
1740                         return -1;
1741                 }
1742                 if (!(p->call = pri_new_call(p->pri->pri))) {
1743                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1744                         pri_rel(p->pri);
1745                         ast_mutex_unlock(&p->lock);
1746                         return -1;
1747                 }
1748                 if (!(sr = pri_sr_new())) {
1749                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1750                         pri_rel(p->pri);
1751                         ast_mutex_unlock(&p->lock);
1752                 }
1753                 if (p->bearer || (p->sig == SIG_FXSKS)) {
1754                         if (p->bearer) {
1755                                 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);
1756                                 p->bearer->call = p->call;
1757                         } else
1758                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
1759                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1760                 }
1761                 p->digital = ast_test_flag(ast,AST_FLAG_DIGITAL);
1762                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1763                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1764                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : PRI_TRANS_CAP_SPEECH, 
1765                                         (p->digital ? -1 : 
1766                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1767                 pri_sr_set_called(sr, c + p->stripmsd, p->pri->dialplan - 1,  s ? 1 : 0);
1768                 pri_sr_set_caller(sr, l, n, p->pri->localdialplan - 1, 
1769                                         l ? (ast->restrictcid ? PRES_PROHIB_USER_NUMBER_PASSED_SCREEN : 
1770                                                 (p->use_callingpres ? ast->callingpres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN)) : 
1771                                                  PRES_NUMBER_NOT_AVAILABLE);
1772                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1773                         ast_log(LOG_WARNING, "Unable to setup call to %s\n", c + p->stripmsd);
1774                         pri_rel(p->pri);
1775                         ast_mutex_unlock(&p->lock);
1776                         pri_sr_free(sr);
1777                         return -1;
1778                 }
1779                 pri_sr_free(sr);
1780                 ast_setstate(ast, AST_STATE_DIALING);
1781                 pri_rel(p->pri);
1782         }
1783 #endif          
1784         ast_mutex_unlock(&p->lock);
1785         return 0;
1786 }
1787
1788 static void destroy_zt_pvt(struct zt_pvt **pvt)
1789 {
1790         struct zt_pvt *p = *pvt;
1791         ast_mutex_destroy(&p->lock);
1792         free(p);
1793         *pvt = NULL;
1794 }
1795
1796 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1797 {
1798         int owned = 0;
1799         int i = 0;
1800
1801         if (!now) {
1802                 if (cur->owner) {
1803                         owned = 1;
1804                 }
1805
1806                 for (i = 0; i < 3; i++) {
1807                         if (cur->subs[i].owner) {
1808                                 owned = 1;
1809                         }
1810                 }
1811                 if (!owned) {
1812                         if (prev) {
1813                                 prev->next = cur->next;
1814                                 if (prev->next)
1815                                         prev->next->prev = prev;
1816                                 else
1817                                         ifend = prev;
1818                         } else {
1819                                 iflist = cur->next;
1820                                 if (iflist)
1821                                         iflist->prev = NULL;
1822                                 else
1823                                         ifend = NULL;
1824                         }
1825                         if (cur->subs[SUB_REAL].zfd > -1) {
1826                                 zt_close(cur->subs[SUB_REAL].zfd);
1827                         }
1828                         destroy_zt_pvt(&cur);
1829                 }
1830         } else {
1831                 if (prev) {
1832                         prev->next = cur->next;
1833                         if (prev->next)
1834                                 prev->next->prev = prev;
1835                         else
1836                                 ifend = prev;
1837                 } else {
1838                         iflist = cur->next;
1839                         if (iflist)
1840                                 iflist->prev = NULL;
1841                         else
1842                                 ifend = NULL;
1843                 }
1844                 if (cur->subs[SUB_REAL].zfd > -1) {
1845                         zt_close(cur->subs[SUB_REAL].zfd);
1846                 }
1847                 destroy_zt_pvt(&cur);
1848         }
1849         return 0;
1850 }
1851
1852 #ifdef ZAPATA_PRI
1853 int pri_is_up(struct zt_pri *pri)
1854 {
1855         int x;
1856         for (x=0;x<NUM_DCHANS;x++) {
1857                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
1858                         return 1;
1859         }
1860         return 0;
1861 }
1862
1863 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
1864 {
1865         bearer->owner = &inuse;
1866         bearer->master = crv;
1867         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
1868         if (crv->subs[SUB_REAL].owner)
1869                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
1870         crv->bearer = bearer;
1871         crv->call = bearer->call;
1872         crv->pri = pri;
1873         return 0;
1874 }
1875
1876 static char *pri_order(int level)
1877 {
1878         switch(level) {
1879         case 0:
1880                 return "Primary";
1881         case 1:
1882                 return "Secondary";
1883         case 2:
1884                 return "Tertiary";
1885         case 3:
1886                 return "Quaternary";
1887         default:
1888                 return "<Unknown>";
1889         }               
1890 }
1891
1892 int pri_find_dchan(struct zt_pri *pri)
1893 {
1894         int oldslot = -1;
1895         struct pri *old;
1896         int newslot = -1;
1897         int x;
1898         old = pri->pri;
1899         for(x=0;x<NUM_DCHANS;x++) {
1900                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
1901                         newslot = x;
1902                 if (pri->dchans[x] == old) {
1903                         oldslot = x;
1904                 }
1905         }
1906         if (newslot < 0) {
1907                 newslot = 0;
1908                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
1909                         pri->dchannels[newslot]);
1910         }
1911         if (old && (oldslot != newslot))
1912                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
1913                         pri->dchannels[oldslot], pri->dchannels[newslot]);
1914         pri->pri = pri->dchans[newslot];
1915         return 0;
1916 }
1917 #endif
1918
1919 static int zt_hangup(struct ast_channel *ast)
1920 {
1921         int res;
1922         int index,x, law;
1923         static int restore_gains(struct zt_pvt *p);
1924         struct zt_pvt *p = ast->pvt->pvt;
1925         struct zt_pvt *tmp = NULL;
1926         struct zt_pvt *prev = NULL;
1927         ZT_PARAMS par;
1928
1929         if (option_debug)
1930                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1931         if (!ast->pvt->pvt) {
1932                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1933                 return 0;
1934         }
1935         
1936         ast_mutex_lock(&p->lock);
1937         
1938         index = zt_get_index(ast, p, 1);
1939
1940         if (p->sig == SIG_PRI) {
1941                 x = 1;
1942                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
1943         }
1944
1945         x = 0;
1946         zt_confmute(p, 0);
1947         restore_gains(p);
1948         if (p->origcallerid) {
1949                 strncpy(p->callerid, p->origcallerid, sizeof(p->callerid) - 1);
1950                 free(p->origcallerid);
1951                 p->origcallerid = NULL;
1952         }       
1953         if (p->dsp)
1954                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
1955         if (p->exten)
1956                 p->exten[0] = '\0';
1957
1958         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1959                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
1960         p->ignoredtmf = 0;
1961         
1962         if (index > -1) {
1963                 /* Real channel, do some fixup */
1964                 p->subs[index].owner = NULL;
1965                 p->subs[index].needanswer = 0;
1966                 p->subs[index].needringing = 0;
1967                 p->subs[index].needbusy = 0;
1968                 p->subs[index].needcongestion = 0;
1969                 p->subs[index].linear = 0;
1970                 p->subs[index].needcallerid = 0;
1971                 zt_setlinear(p->subs[index].zfd, 0);
1972                 if (index == SUB_REAL) {
1973                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
1974                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
1975                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
1976                                         /* We had flipped over to answer a callwait and now it's gone */
1977                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
1978                                         /* Move to the call-wait, but un-own us until they flip back. */
1979                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1980                                         unalloc_sub(p, SUB_CALLWAIT);
1981                                         p->owner = NULL;
1982                                 } else {
1983                                         /* The three way hung up, but we still have a call wait */
1984                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1985                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
1986                                         unalloc_sub(p, SUB_THREEWAY);
1987                                         if (p->subs[SUB_REAL].inthreeway) {
1988                                                 /* This was part of a three way call.  Immediately make way for
1989                                                    another call */
1990                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1991                                                 p->owner = p->subs[SUB_REAL].owner;
1992                                         } else {
1993                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1994                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1995                                                 p->owner = NULL;
1996                                         }
1997                                         p->subs[SUB_REAL].inthreeway = 0;
1998                                 }
1999                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2000                                 /* Move to the call-wait and switch back to them. */
2001                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2002                                 unalloc_sub(p, SUB_CALLWAIT);
2003                                 p->owner = p->subs[SUB_REAL].owner;
2004                                 if (p->owner->_state != AST_STATE_UP)
2005                                         p->subs[SUB_REAL].needanswer = 1;
2006                                 if (p->subs[SUB_REAL].owner->bridge)
2007                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
2008                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2009                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2010                                 unalloc_sub(p, SUB_THREEWAY);
2011                                 if (p->subs[SUB_REAL].inthreeway) {
2012                                         /* This was part of a three way call.  Immediately make way for
2013                                            another call */
2014                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2015                                         p->owner = p->subs[SUB_REAL].owner;
2016                                 } else {
2017                                         /* This call hasn't been completed yet...  Set owner to NULL */
2018                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2019                                         p->owner = NULL;
2020                                 }
2021                                 p->subs[SUB_REAL].inthreeway = 0;
2022                         }
2023                 } else if (index == SUB_CALLWAIT) {
2024                         /* Ditch the holding callwait call, and immediately make it availabe */
2025                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2026                                 /* This is actually part of a three way, placed on hold.  Place the third part
2027                                    on music on hold now */
2028                                 if (p->subs[SUB_THREEWAY].owner && p->subs[SUB_THREEWAY].owner->bridge)
2029                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
2030                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2031                                 /* Make it the call wait now */
2032                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2033                                 unalloc_sub(p, SUB_THREEWAY);
2034                         } else
2035                                 unalloc_sub(p, SUB_CALLWAIT);
2036                 } else if (index == SUB_THREEWAY) {
2037                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2038                                 /* The other party of the three way call is currently in a call-wait state.
2039                                    Start music on hold for them, and take the main guy out of the third call */
2040                                 if (p->subs[SUB_CALLWAIT].owner && p->subs[SUB_CALLWAIT].owner->bridge)
2041                                         ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
2042                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2043                         }
2044                         p->subs[SUB_REAL].inthreeway = 0;
2045                         /* If this was part of a three way call index, let us make
2046                            another three way call */
2047                         unalloc_sub(p, SUB_THREEWAY);
2048                 } else {
2049                         /* This wasn't any sort of call, but how are we an index? */
2050                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2051                 }
2052         }
2053
2054
2055         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2056                 p->owner = NULL;
2057                 p->ringt = 0;
2058                 p->distinctivering = 0;
2059                 p->confirmanswer = 0;
2060                 p->cidrings = 1;
2061                 p->outgoing = 0;
2062                 p->digital = 0;
2063                 p->faxhandled = 0;
2064                 p->pulsedial = 0;
2065                 p->onhooktime = time(NULL);
2066 #ifdef ZAPATA_PRI
2067                 p->proceeding = 0;
2068                 p->setup_ack = 0;
2069 #endif          
2070                 if (p->dsp) {
2071                         ast_dsp_free(p->dsp);
2072                         p->dsp = NULL;
2073                 }
2074
2075                 law = ZT_LAW_DEFAULT;
2076                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2077                 if (res < 0) 
2078                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2079                 /* Perform low level hangup if no owner left */
2080 #ifdef ZAPATA_PRI
2081                 if (p->pri) {
2082                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2083                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2084                                 if (!pri_grab(p, p->pri)) {
2085                                         if (p->alreadyhungup) {
2086                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2087                                                 pri_hangup(p->pri->pri, p->call, -1);
2088                                                 p->call = NULL;
2089                                                 if (p->bearer) 
2090                                                         p->bearer->call = NULL;
2091                                         } else {
2092                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2093                                                 int icause = ast->hangupcause ? hangup_cause2pri(ast->hangupcause) : -1;
2094                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2095                                                 p->alreadyhungup = 1;
2096                                                 if (p->bearer)
2097                                                         p->bearer->alreadyhungup = 1;
2098                                                 if (cause) {
2099                                                         if (atoi(cause))
2100                                                                 icause = atoi(cause);
2101                                                 }
2102                                                 pri_hangup(p->pri->pri, p->call, icause);
2103                                         }
2104                                         if (res < 0) 
2105                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2106                                         pri_rel(p->pri);                        
2107                                 } else {
2108                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2109                                         res = -1;
2110                                 }
2111                         } else {
2112                                 if (p->bearer)
2113                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2114                                 p->call = NULL;
2115                                 res = 0;
2116                         }
2117                 }
2118 #endif
2119 #ifdef ZAPATA_R2
2120                 if (p->sig == SIG_R2) {
2121                         if (p->hasr2call) {
2122                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2123                                 p->hasr2call = 0;
2124                                 res = 0;
2125                         } else
2126                                 res = 0;
2127
2128                 }
2129 #endif
2130                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2131                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2132                 if (res < 0) {
2133                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2134                 }
2135                 switch(p->sig) {
2136                 case SIG_FXOGS:
2137                 case SIG_FXOLS:
2138                 case SIG_FXOKS:
2139                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2140                         if (!res) {
2141 #if 0
2142                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2143 #endif
2144                                 /* If they're off hook, try playing congestion */
2145                                 if (par.rxisoffhook)
2146                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2147                                 else
2148                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2149                         }
2150                         break;
2151                 case SIG_FXSGS:
2152                 case SIG_FXSLS:
2153                 case SIG_FXSKS:
2154                         /* Make sure we're not made available for at least two seconds */
2155                         time(&p->guardtime);
2156                         p->guardtime += 2;
2157                         break;
2158                 default:
2159                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2160                 }
2161                 if (p->cidspill)
2162                         free(p->cidspill);
2163                 if (p->sig)
2164                         zt_disable_ec(p);
2165                 x = 0;
2166                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2167                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2168                 p->didtdd = 0;
2169                 p->cidspill = NULL;
2170                 p->callwaitcas = 0;
2171                 p->callwaiting = p->permcallwaiting;
2172                 p->hidecallerid = p->permhidecallerid;
2173                 p->dialing = 0;
2174                 p->rdnis[0] = '\0';
2175                 update_conf(p);
2176                 /* Restore data mode */
2177                 if (p->sig == SIG_PRI) {
2178                         x = 0;
2179                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2180                 }
2181 #ifdef ZAPATA_PRI
2182                 if (p->bearer) {
2183                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2184                         /* Free up the bearer channel as well, and
2185                            don't use its file descriptor anymore */
2186                         p->bearer->owner = NULL;
2187                         p->bearer = NULL;
2188                         p->subs[SUB_REAL].zfd = -1;
2189                         p->pri = NULL;
2190                 }
2191 #endif
2192                 restart_monitor();
2193         }
2194
2195
2196         p->callwaitingrepeat = 0;
2197         p->cidcwexpire = 0;
2198         ast->pvt->pvt = NULL;
2199         ast_mutex_unlock(&p->lock);
2200         ast_mutex_lock(&usecnt_lock);
2201         usecnt--;
2202         if (usecnt < 0) 
2203                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2204         ast_mutex_unlock(&usecnt_lock);
2205         ast_update_use_count();
2206         if (option_verbose > 2) 
2207                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2208
2209         ast_mutex_lock(&iflock);
2210         tmp = iflist;
2211         prev = NULL;
2212         if (p->destroy) {
2213                 while (tmp) {
2214                         if (tmp == p) {
2215                                 destroy_channel(prev, tmp, 0);
2216                                 break;
2217                         } else {
2218                                 prev = tmp;
2219                                 tmp = tmp->next;
2220                         }
2221                 }
2222         }
2223         ast_mutex_unlock(&iflock);
2224         return 0;
2225 }
2226
2227 static int zt_answer(struct ast_channel *ast)
2228 {
2229         struct zt_pvt *p = ast->pvt->pvt;
2230         int res=0;
2231         int index;
2232         int oldstate = ast->_state;
2233         ast_setstate(ast, AST_STATE_UP);
2234         ast_mutex_lock(&p->lock);
2235         index = zt_get_index(ast, p, 0);
2236         if (index < 0)
2237                 index = SUB_REAL;
2238         /* nothing to do if a radio channel */
2239         if (p->radio) {
2240                 ast_mutex_unlock(&p->lock);
2241                 return 0;
2242         }
2243         switch(p->sig) {
2244         case SIG_FXSLS:
2245         case SIG_FXSGS:
2246         case SIG_FXSKS:
2247                 p->ringt = 0;
2248                 /* Fall through */
2249         case SIG_EM:
2250         case SIG_EM_E1:
2251         case SIG_EMWINK:
2252         case SIG_FEATD:
2253         case SIG_FEATDMF:
2254         case SIG_E911:
2255         case SIG_FEATB:
2256         case SIG_SF:
2257         case SIG_SFWINK:
2258         case SIG_SF_FEATD:
2259         case SIG_SF_FEATDMF:
2260         case SIG_SF_FEATB:
2261         case SIG_FXOLS:
2262         case SIG_FXOGS:
2263         case SIG_FXOKS:
2264                 /* Pick up the line */
2265                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2266                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2267                 tone_zone_play_tone(p->subs[index].zfd, -1);
2268                 p->dialing = 0;
2269                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2270                         if (oldstate == AST_STATE_RINGING) {
2271                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2272                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2273                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2274                                 p->owner = p->subs[SUB_REAL].owner;
2275                         }
2276                 }
2277                 if (p->sig & __ZT_SIG_FXS) {
2278                         zt_enable_ec(p);
2279                         zt_train_ec(p);
2280                 }
2281                 break;
2282 #ifdef ZAPATA_PRI
2283         case SIG_PRI:
2284                 /* Send a pri acknowledge */
2285                 if (!pri_grab(p, p->pri)) {
2286                         p->proceeding = 2;
2287                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2288                         pri_rel(p->pri);
2289                 } else {
2290                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2291                         res= -1;
2292                 }
2293                 break;
2294 #endif
2295 #ifdef ZAPATA_R2
2296         case SIG_R2:
2297                 res = mfcr2_AnswerCall(p->r2, NULL);
2298                 if (res)
2299                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2300                 break;
2301 #endif                  
2302         case 0:
2303                 ast_mutex_unlock(&p->lock);
2304                 return 0;
2305         default:
2306                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2307                 res = -1;
2308         }
2309         ast_mutex_unlock(&p->lock);
2310         return res;
2311 }
2312
2313 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2314 {
2315 char    *cp;
2316 int     x;
2317
2318         struct zt_pvt *p = chan->pvt->pvt;
2319
2320         
2321         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2322                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2323            {
2324                 errno = ENOSYS;
2325                 return -1;
2326            }
2327         cp = (char *)data;
2328         if ((!cp) || (datalen < 1))
2329            {
2330                 errno = EINVAL;
2331                 return -1;
2332            }
2333         switch(option) {
2334             case AST_OPTION_TONE_VERIFY:
2335                 if (!p->dsp)
2336                         break;
2337                 switch(*cp) {
2338                     case 1:
2339                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2340                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2341                         break;
2342                     case 2:
2343                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2344                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2345                         break;
2346                     default:
2347                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2348                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2349                         break;
2350                 }
2351                 break;
2352             case AST_OPTION_TDD:  /* turn on or off TDD */
2353                 if (!*cp) { /* turn it off */
2354                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2355                         if (p->tdd) tdd_free(p->tdd);
2356                         p->tdd = 0;
2357                         p->mate = 0;
2358                         break;
2359                 }
2360                 if (*cp == 2)
2361                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2362                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2363                 p->mate = 0;
2364                 zt_disable_ec(p);
2365                 /* otherwise, turn it on */
2366                 if (!p->didtdd) { /* if havent done it yet */
2367                         unsigned char mybuf[41000],*buf;
2368                         int size,res,fd,len;
2369                         int index;
2370                         struct pollfd fds[1];
2371                         buf = mybuf;
2372                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2373                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2374                         len = 40000;
2375                         index = zt_get_index(chan, p, 0);
2376                         if (index < 0) {
2377                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2378                                 return -1;
2379                         }
2380                         fd = p->subs[index].zfd;
2381                         while(len) {
2382                                 if (ast_check_hangup(chan)) return -1;
2383                                 size = len;
2384                                 if (size > READ_SIZE)
2385                                         size = READ_SIZE;
2386                                 fds[0].fd = fd;
2387                                 fds[0].events = POLLPRI | POLLOUT;
2388                                 res = poll(fds, 1, -1);
2389                                 if (!res) {
2390                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2391                                         continue;
2392                                 }
2393                                   /* if got exception */
2394                                 if (fds[0].revents & POLLPRI) return -1;
2395                                 if (!(fds[0].revents & POLLOUT)) {
2396                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2397                                         continue;
2398                                 }
2399                                 res = write(fd, buf, size);
2400                                 if (res != size) {
2401                                         if (res == -1) return -1;
2402                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2403                                         break;
2404                                 }
2405                                 len -= size;
2406                                 buf += size;
2407                         }
2408                         p->didtdd = 1; /* set to have done it now */            
2409                 }
2410                 if (*cp == 2) { /* Mate mode */
2411                         if (p->tdd) tdd_free(p->tdd);
2412                         p->tdd = 0;
2413                         p->mate = 1;
2414                         break;
2415                         }               
2416                 if (!p->tdd) { /* if we dont have one yet */
2417                         p->tdd = tdd_new(); /* allocate one */
2418                 }               
2419                 break;
2420             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2421                 if (!*cp)
2422                 {               
2423                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2424                         x = 0;
2425                 }
2426                 else
2427                 {               
2428                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2429                         x = 1;
2430                 }
2431                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2432                 break;
2433             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2434                 if (!*cp)
2435                 {               
2436                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2437                         x = 0;
2438                         zt_disable_ec(p);
2439                 }
2440                 else
2441                 {               
2442                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2443                         x = 1;
2444                 }
2445                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2446                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2447                 break;
2448         }
2449         errno = 0;
2450         return 0;
2451 }
2452
2453 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2454 {
2455         /* Unlink a specific slave or all slaves/masters from a given master */
2456         int x;
2457         int hasslaves;
2458         if (!master)
2459                 return;
2460         if (needlock) {
2461                 ast_mutex_lock(&master->lock);
2462                 if (slave) {
2463                         while(ast_mutex_trylock(&slave->lock)) {
2464                                 ast_mutex_unlock(&master->lock);
2465                                 usleep(1);
2466                                 ast_mutex_lock(&master->lock);
2467                         }
2468                 }
2469         }
2470         hasslaves = 0;
2471         for (x=0;x<MAX_SLAVES;x++) {
2472                 if (master->slaves[x]) {
2473                         if (!slave || (master->slaves[x] == slave)) {
2474                                 /* Take slave out of the conference */
2475                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2476                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2477                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2478                                 master->slaves[x]->master = NULL;
2479                                 master->slaves[x] = NULL;
2480                         } else
2481                                 hasslaves = 1;
2482                 }
2483                 if (!hasslaves)
2484                         master->inconference = 0;
2485         }
2486         if (!slave) {
2487                 if (master->master) {
2488                         /* Take master out of the conference */
2489                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2490                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2491                         hasslaves = 0;
2492                         for (x=0;x<MAX_SLAVES;x++) {
2493                                 if (master->master->slaves[x] == master)
2494                                         master->master->slaves[x] = NULL;
2495                                 else if (master->master->slaves[x])
2496                                         hasslaves = 1;
2497                         }
2498                         if (!hasslaves)
2499                                 master->master->inconference = 0;
2500                 }
2501                 master->master = NULL;
2502         }
2503         update_conf(master);
2504         if (needlock) {
2505                 if (slave)
2506                         ast_mutex_unlock(&slave->lock);
2507                 ast_mutex_unlock(&master->lock);
2508         }
2509 }
2510
2511 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2512         int x;
2513         if (!slave || !master) {
2514                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2515                 return;
2516         }
2517         for (x=0;x<MAX_SLAVES;x++) {
2518                 if (!master->slaves[x]) {
2519                         master->slaves[x] = slave;
2520                         break;
2521                 }
2522         }
2523         if (x >= MAX_SLAVES) {
2524                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2525                 master->slaves[MAX_SLAVES - 1] = slave;
2526         }
2527         if (slave->master) 
2528                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2529         slave->master = master;
2530         
2531         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2532 }
2533
2534 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2535 {
2536         struct ast_channel *who = NULL, *cs[3];
2537         struct zt_pvt *p0, *p1, *op0, *op1;
2538         struct zt_pvt *master=NULL, *slave=NULL;
2539         struct ast_frame *f;
2540         int to;
2541         int inconf = 0;
2542         int nothingok = 0;
2543         int ofd1, ofd2;
2544         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2545         int os1 = -1, os2 = -1;
2546         struct ast_channel *oc1, *oc2;
2547
2548         /* if need DTMF, cant native bridge */
2549         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2550                 return -2;
2551                 
2552         ast_mutex_lock(&c0->lock);
2553         ast_mutex_lock(&c1->lock);
2554
2555         p0 = c0->pvt->pvt;
2556         p1 = c1->pvt->pvt;
2557         /* cant do pseudo-channels here */
2558         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2559                 ast_mutex_unlock(&c0->lock);
2560                 ast_mutex_unlock(&c1->lock);
2561                 return -2;
2562         }
2563
2564         op0 = p0 = c0->pvt->pvt;
2565         op1 = p1 = c1->pvt->pvt;
2566         ofd1 = c0->fds[0];
2567         ofd2 = c1->fds[0];
2568         oi1 = zt_get_index(c0, p0, 0);
2569         oi2 = zt_get_index(c1, p1, 0);
2570         oc1 = p0->owner;
2571         oc2 = p1->owner;
2572         if ((oi1 < 0) || (oi2 < 0)) {
2573                 ast_mutex_unlock(&c0->lock);
2574                 ast_mutex_unlock(&c1->lock);
2575                 return -1;
2576         }
2577
2578
2579
2580         ast_mutex_lock(&p0->lock);
2581         if (ast_mutex_trylock(&p1->lock)) {
2582                 /* Don't block, due to potential for deadlock */
2583                 ast_mutex_unlock(&p0->lock);
2584                 ast_mutex_unlock(&c0->lock);
2585                 ast_mutex_unlock(&c1->lock);
2586                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2587                 return -3;
2588         }
2589         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2590                 if (!p0->owner || !p1->owner) {
2591                         /* Currently unowned -- Do nothing.  */
2592                         nothingok = 1;
2593                 } else {
2594                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2595                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2596                                 master = p0;
2597                                 slave = p1;
2598                                 inconf = 1;
2599                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2600                                 master = p1;
2601                                 slave = p0;
2602                                 inconf = 1;
2603                         } else {
2604                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2605                                 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,
2606                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2607                         }
2608                 }
2609         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2610                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2611                         master = p1;
2612                         slave = p0;
2613                 } else {
2614                         nothingok = 1;
2615                 }
2616         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2617                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2618                         master = p0;
2619                         slave = p1;
2620                 } else {
2621                         nothingok  = 1;
2622                 }
2623         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2624                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2625                    don't put us in anything */
2626                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2627                         master = p1;
2628                         slave = p0;
2629                 } else {
2630                         nothingok = 1;
2631                 }
2632         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2633                 /* Same as previous */
2634                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2635                         master = p0;
2636                         slave = p1;
2637                 } else {
2638                         nothingok = 1;
2639                 }
2640         }
2641         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2642                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2643         if (master && slave) {
2644                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2645                    in an active threeway call with a channel that is ringing, we should
2646                    indicate ringing. */
2647                 if ((oi2 == SUB_THREEWAY) && 
2648                         p1->subs[SUB_THREEWAY].inthreeway && 
2649                         p1->subs[SUB_REAL].owner && 
2650                         p1->subs[SUB_REAL].inthreeway && 
2651                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2652                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2653                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2654                                 os2 = p1->subs[SUB_REAL].owner->_state;
2655                 } else {
2656                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2657                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2658                 }
2659                 if ((oi1 == SUB_THREEWAY) && 
2660                         p0->subs[SUB_THREEWAY].inthreeway && 
2661                         p0->subs[SUB_REAL].owner && 
2662                         p0->subs[SUB_REAL].inthreeway && 
2663                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2664                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2665                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2666                                 os1 = p0->subs[SUB_REAL].owner->_state;
2667                 } else {
2668                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2669                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2670                 }
2671                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2672                         if (!p0->echocanbridged || !p1->echocanbridged) {
2673                                 /* Disable echo cancellation if appropriate */
2674                                 zt_disable_ec(p0);
2675                                 zt_disable_ec(p1);
2676                         }
2677                 }
2678                 zt_link(slave, master);
2679                 master->inconference = inconf;
2680         } else if (!nothingok)
2681                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2682
2683         update_conf(p0);
2684         update_conf(p1);
2685         t1 = p0->subs[SUB_REAL].inthreeway;
2686         t2 = p1->subs[SUB_REAL].inthreeway;
2687
2688         ast_mutex_unlock(&p0->lock);
2689         ast_mutex_unlock(&p1->lock);
2690
2691         ast_mutex_unlock(&c0->lock);
2692         ast_mutex_unlock(&c1->lock);
2693
2694         /* Native bridge failed */
2695         if ((!master || !slave) && !nothingok) {
2696                 if (op0 == p0)
2697                         zt_enable_ec(p0);
2698                 if (op1 == p1)
2699                         zt_enable_ec(p1);
2700                 return -1;
2701         }
2702         
2703         cs[0] = c0;
2704         cs[1] = c1;
2705         cs[2] = NULL;
2706         for (;;) {
2707                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2708                    and then balking if anything is wrong */
2709                 ast_mutex_lock(&c0->lock);
2710                 ast_mutex_lock(&c1->lock);
2711                 p0 = c0->pvt->pvt;
2712                 p1 = c1->pvt->pvt;
2713                 if (op0 == p0)
2714                         i1 = zt_get_index(c0, p0, 1);
2715                 if (op1 == p1)
2716                         i2 = zt_get_index(c1, p1, 1);
2717                 ast_mutex_unlock(&c0->lock);
2718                 ast_mutex_unlock(&c1->lock);
2719                 if ((op0 != p0) || (op1 != p1) || 
2720                     (ofd1 != c0->fds[0]) || 
2721                         (ofd2 != c1->fds[0]) ||
2722                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2723                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2724                     (oc1 != p0->owner) || 
2725                         (oc2 != p1->owner) ||
2726                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2727                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2728                         (oi1 != i1) ||
2729                         (oi2 != i2)) {
2730                         if (slave && master)
2731                                 zt_unlink(slave, master, 1);
2732                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2733                                                                         op0->channel, oi1, op1->channel, oi2);
2734                         if (op0 == p0)
2735                                 zt_enable_ec(p0);
2736                         if (op1 == p1)
2737                                 zt_enable_ec(p1);
2738                         return -3;
2739                 }
2740                 to = -1;
2741                 who = ast_waitfor_n(cs, 2, &to);
2742                 if (!who) {
2743                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2744                         continue;
2745                 }
2746                 if (who->pvt->pvt == op0) 
2747                         op0->ignoredtmf = 1;
2748                 else if (who->pvt->pvt == op1)
2749                         op1->ignoredtmf = 1;
2750                 f = ast_read(who);
2751                 if (who->pvt->pvt == op0) 
2752                         op0->ignoredtmf = 0;
2753                 else if (who->pvt->pvt == op1)
2754                         op1->ignoredtmf = 0;
2755                 if (!f) {
2756                         *fo = NULL;
2757                         *rc = who;
2758                         if (slave && master)
2759                                 zt_unlink(slave, master, 1);
2760                         if (op0 == p0)
2761                                 zt_enable_ec(p0);
2762                         if (op1 == p1)
2763                                 zt_enable_ec(p1);
2764                         return 0;
2765                 }
2766                 if (f->frametype == AST_FRAME_DTMF) {
2767                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2768                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2769                                 *fo = f;
2770                                 *rc = who;
2771                                 if (slave && master)
2772                                         zt_unlink(slave, master, 1);
2773                                 return 0;
2774                         } else if ((who == c0) && p0->pulsedial) {
2775                                 ast_write(c1, f);
2776                         } else if ((who == c1) && p1->pulsedial) {
2777                                 ast_write(c0, f);
2778                         }
2779                 }
2780                 ast_frfree(f);
2781
2782                 /* Swap who gets priority */
2783                 cs[2] = cs[0];
2784                 cs[0] = cs[1];
2785                 cs[1] = cs[2];
2786         }
2787 }
2788
2789 static int zt_indicate(struct ast_channel *chan, int condition);
2790
2791 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2792 {
2793         struct zt_pvt *p = newchan->pvt->pvt;
2794         int x;
2795         ast_mutex_lock(&p->lock);
2796         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2797         if (p->owner == oldchan) {
2798                 p->owner = newchan;
2799         }
2800         for (x=0;x<3;x++)
2801                 if (p->subs[x].owner == oldchan) {
2802                         if (!x)
2803                                 zt_unlink(NULL, p, 0);
2804                         p->subs[x].owner = newchan;
2805                 }
2806         if (newchan->_state == AST_STATE_RINGING) 
2807                 zt_indicate(newchan, AST_CONTROL_RINGING);
2808         update_conf(p);
2809         ast_mutex_unlock(&p->lock);
2810         return 0;
2811 }
2812
2813 static int zt_ring_phone(struct zt_pvt *p)
2814 {
2815         int x;
2816         int res;
2817         /* Make sure our transmit state is on hook */
2818         x = 0;
2819         x = ZT_ONHOOK;
2820         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2821         do {
2822                 x = ZT_RING;
2823                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2824 #if 0
2825                 printf("Res: %d, error: %s\n", res, strerror(errno));
2826 #endif                                          
2827                 if (res) {
2828                         switch(errno) {
2829                         case EBUSY:
2830                         case EINTR:
2831                                 /* Wait just in case */
2832                                 usleep(10000);
2833                                 continue;
2834                         case EINPROGRESS:
2835                                 res = 0;
2836                                 break;
2837                         default:
2838                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2839                                 res = 0;
2840                         }
2841                 }
2842         } while (res);
2843         return res;
2844 }
2845
2846 static void *ss_thread(void *data);
2847
2848 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2849
2850 static int attempt_transfer(struct zt_pvt *p)
2851 {
2852         /* In order to transfer, we need at least one of the channels to
2853            actually be in a call bridge.  We can't conference two applications
2854            together (but then, why would we want to?) */
2855         if (p->subs[SUB_REAL].owner->bridge) {
2856                 /* The three-way person we're about to transfer to could still be in MOH, so
2857                    stop if now if appropriate */
2858                 if (p->subs[SUB_THREEWAY].owner->bridge)
2859                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2860                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2861                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2862                 }
2863                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2864                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2865                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2866                         return -1;
2867                 }
2868                 /* Orphan the channel */
2869                 unalloc_sub(p, SUB_THREEWAY);
2870         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2871                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2872                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2873                 }
2874                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2875                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2876                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2877                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2878                         return -1;
2879                 }
2880                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2881                 unalloc_sub(p, SUB_THREEWAY);
2882                 /* Tell the caller not to hangup */
2883                 return 1;
2884         } else {
2885                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2886                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2887                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2888         }
2889         return 0;
2890 }
2891
2892 #ifdef ZAPATA_R2
2893 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2894 {
2895         struct ast_frame *f;
2896         f = &p->subs[index].f;
2897         if (!p->r2) {
2898                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2899                 return NULL;
2900         }
2901         switch(e->e) {
2902         case MFCR2_EVENT_BLOCKED:
2903                 if (option_verbose > 2)
2904                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2905                 break;
2906         case MFCR2_EVENT_UNBLOCKED:
2907                 if (option_verbose > 2)
2908                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2909                 break;
2910         case MFCR2_EVENT_CONFIG_ERR:
2911                 if (option_verbose > 2)
2912                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2913                 break;
2914         case MFCR2_EVENT_RING:
2915                 if (option_verbose > 2)
2916                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2917                 break;
2918         case MFCR2_EVENT_HANGUP:
2919                 if (option_verbose > 2)
2920                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2921                 break;
2922         case MFCR2_EVENT_RINGING:
2923                 if (option_verbose > 2)
2924                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2925                 break;
2926         case MFCR2_EVENT_ANSWER:
2927                 if (option_verbose > 2)
2928                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2929                 break;
2930         case MFCR2_EVENT_HANGUP_ACK:
2931                 if (option_verbose > 2)
2932                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2933                 break;
2934         case MFCR2_EVENT_IDLE:
2935                 if (option_verbose > 2)
2936                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2937                 break;
2938         default:
2939                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2940                 break;
2941         }
2942         return f;
2943 }
2944
2945 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2946 {
2947         int x;
2948         int res;
2949         mfcr2_event_t *e;
2950         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2951         if (res) {
2952                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2953                 return NULL;
2954         }
2955         if (!p->r2) {
2956                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2957                 return NULL;
2958         }
2959         e = mfcr2_cas_signaling_event(p->r2, x);
2960         return e;
2961 }
2962 #endif
2963
2964 static int check_for_conference(struct zt_pvt *p)
2965 {
2966         ZT_CONFINFO ci;
2967         /* Fine if we already have a master, etc */
2968         if (p->master || (p->confno > -1))
2969                 return 0;
2970         memset(&ci, 0, sizeof(ci));
2971         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2972                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2973                 return 0;
2974         }
2975         /* If we have no master and don't have a confno, then 
2976            if we're in a conference, it's probably a MeetMe room or
2977            some such, so don't let us 3-way out! */
2978         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
2979                 if (option_verbose > 2) 
2980                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2981                 return 1;
2982         }
2983         return 0;
2984 }
2985
2986 static int get_alarms(struct zt_pvt *p)
2987 {
2988         int res;
2989         ZT_SPANINFO zi;
2990         memset(&zi, 0, sizeof(zi));
2991         zi.spanno = p->span;
2992         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2993         if (res < 0) {