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