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