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