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