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