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