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