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