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