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