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