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