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