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