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