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