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