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