Add missing break
[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 <sys/select.h>
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <unistd.h>
48 #include <sys/ioctl.h>
49 #include <linux/zaptel.h>
50 #include <math.h>
51 #include <tonezone.h>
52 #include <ctype.h>
53 #ifdef ZAPATA_PRI
54 #include <libpri.h>
55 #endif
56 #ifdef ZAPATA_R2
57 #include <libmfcr2.h>
58 #endif
59
60 #include "../asterisk.h"
61
62 /* 
63    XXX 
64    XXX   We definitely need to lock the private structure in zt_read and such 
65    XXX  
66  */
67
68
69 /*
70  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
71  * the user hangs up to reset the state machine so ring works properly.
72  * This is used to be able to support kewlstart by putting the zhone in
73  * groundstart mode since their forward disconnect supervision is entirely
74  * broken even though their documentation says it isn't and their support
75  * is entirely unwilling to provide any assistance with their channel banks
76  * even though their web site says they support their products for life.
77  */
78
79 /* #define ZHONE_HACK */
80
81 /* Typically, how many rings before we should send Caller*ID */
82 #define DEFAULT_CIDRINGS 1
83
84 #define CHANNEL_PSEUDO -12
85
86 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
87
88 static char *desc = "Zapata Telephony"
89 #ifdef ZAPATA_PRI
90                " w/PRI"
91 #endif
92 #ifdef ZAPATA_R2
93                " w/R2"
94 #endif
95 ;
96
97 static char *tdesc = "Zapata Telephony Driver"
98 #ifdef ZAPATA_PRI
99                " w/PRI"
100 #endif
101 #ifdef ZAPATA_R2
102                " w/R2"
103 #endif
104 ;
105
106 static char *type = "Zap";
107 static char *typecompat = "Tor";        /* Retain compatibility with chan_tor */
108 static char *config = "zapata.conf";
109
110 #define SIG_EM          ZT_SIG_EM
111 #define SIG_EMWINK      (0x100000 | ZT_SIG_EM)
112 #define SIG_FEATD       (0x200000 | ZT_SIG_EM)
113 #define SIG_FEATDMF     (0x400000 | ZT_SIG_EM)
114 #define SIG_FEATB       (0x800000 | ZT_SIG_EM)
115 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
116 #define SIG_FXSLS       ZT_SIG_FXSLS
117 #define SIG_FXSGS       ZT_SIG_FXSGS
118 #define SIG_FXSKS       ZT_SIG_FXSKS
119 #define SIG_FXOLS       ZT_SIG_FXOLS
120 #define SIG_FXOGS       ZT_SIG_FXOGS
121 #define SIG_FXOKS       ZT_SIG_FXOKS
122 #define SIG_PRI         ZT_SIG_CLEAR
123 #define SIG_R2          ZT_SIG_CAS
124 #define SIG_SF          ZT_SIG_SF
125 #define SIG_SFWINK      (0x100000 | ZT_SIG_SF)
126 #define SIG_SF_FEATD    (0x200000 | ZT_SIG_SF)
127 #define SIG_SF_FEATDMF  (0x400000 | ZT_SIG_SF)
128 #define SIG_SF_FEATB    (0x800000 | ZT_SIG_SF)
129 #define SIG_EM_E1       ZT_SIG_EM_E1
130
131 #define NUM_SPANS       32
132 #define RESET_INTERVAL  3600    /* How often (in seconds) to reset unused channels */
133
134 #define CHAN_PSEUDO     -2
135
136 static char context[AST_MAX_EXTENSION] = "default";
137 static char callerid[256] = "";
138
139 static char language[MAX_LANGUAGE] = "";
140 static char musicclass[MAX_LANGUAGE] = "";
141 static char progzone[10]= "";
142
143 static int usedistinctiveringdetection = 0;
144
145 static int use_callerid = 1;
146 static int zaptrcallerid = 0;
147 static int cur_signalling = -1;
148
149 static unsigned int cur_group = 0;
150 static unsigned int cur_callergroup = 0;
151 static unsigned int cur_pickupgroup = 0;
152 static int relaxdtmf = 0;
153
154 static int immediate = 0;
155
156 static int stripmsd = 0;
157
158 static int callwaiting = 0;
159
160 static int callwaitingcallerid = 0;
161
162 static int hidecallerid = 0;
163
164 static int restrictcid = 0;
165
166 static int use_callingpres = 0;
167
168 static int callreturn = 0;
169
170 static int threewaycalling = 0;
171
172 static int transfer = 0;
173
174 static int cancallforward = 0;
175
176 static float rxgain = 0.0;
177
178 static float txgain = 0.0;
179
180 static int tonezone = -1;
181
182 static int echocancel;
183
184 static int echotraining;
185
186 static int echocanbridged = 0;
187
188 static int busydetect = 0;
189
190 static int busycount = 3;
191
192 static int callprogress = 0;
193
194 static char accountcode[20] = "";
195
196 static char mailbox[AST_MAX_EXTENSION];
197
198 static int amaflags = 0;
199
200 static int adsi = 0;
201
202 static int numbufs = 4;
203
204 static int cur_prewink = -1;
205 static int cur_preflash = -1;
206 static int cur_wink = -1;
207 static int cur_flash = -1;
208 static int cur_start = -1;
209 static int cur_rxwink = -1;
210 static int cur_rxflash = -1;
211 static int cur_debounce = -1;
212
213 #ifdef ZAPATA_PRI
214 static int minunused = 2;
215 static int minidle = 0;
216 static char idleext[AST_MAX_EXTENSION];
217 static char idledial[AST_MAX_EXTENSION];
218 static int overlapdial = 0;
219 #endif
220
221 /* Wait up to 16 seconds for first digit (FXO logic) */
222 static int firstdigittimeout = 16000;
223
224 /* How long to wait for following digits (FXO logic) */
225 static int gendigittimeout = 8000;
226
227 /* How long to wait for an extra digit, if there is an ambiguous match */
228 static int matchdigittimeout = 3000;
229
230 static int usecnt =0;
231 static ast_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
232
233 /* Protect the interface list (of zt_pvt's) */
234 static ast_mutex_t iflock = AST_MUTEX_INITIALIZER;
235
236 /* Protect the monitoring thread, so only one process can kill or start it, and not
237    when it's doing something critical. */
238 static ast_mutex_t monlock = AST_MUTEX_INITIALIZER;
239
240 /* This is the thread for the monitor which checks for input on the channels
241    which are not currently in use.  */
242 static pthread_t monitor_thread = AST_PTHREADT_NULL;
243
244 static int restart_monitor(void);
245
246 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
247
248 static int zt_sendtext(struct ast_channel *c, char *text);
249
250 static inline int zt_get_event(int fd)
251 {
252         /* Avoid the silly zt_getevent which ignores a bunch of events */
253         int j;
254         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
255         return j;
256 }
257
258 static inline int zt_wait_event(int fd)
259 {
260         /* Avoid the silly zt_waitevent which ignores a bunch of events */
261         int i,j=0;
262         i = ZT_IOMUX_SIGEVENT;
263         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
264         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
265         return j;
266 }
267
268 /* Chunk size to read -- we use 20ms chunks to make things happy.  */   
269 #define READ_SIZE 160
270
271 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
272 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
273
274 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
275 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
276 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /* 500 ms */
277 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /* 2000 ms */
278 #define RINGT                                           ( (8000 * 8) / READ_SIZE)
279
280 struct zt_pvt;
281
282
283 #ifdef ZAPATA_R2
284 static int r2prot = -1;
285 #endif
286
287
288 #ifdef ZAPATA_PRI
289 struct zt_pri {
290         pthread_t master;                       /* Thread of master */
291         ast_mutex_t lock;               /* Mutex */
292         char idleext[AST_MAX_EXTENSION];                /* Where to idle extra calls */
293         char idlecontext[AST_MAX_EXTENSION];            /* What context to use for idle */
294         char idledial[AST_MAX_EXTENSION];               /* What to dial before dumping */
295         int minunused;                          /* Min # of channels to keep empty */
296         int minidle;                            /* Min # of "idling" calls to keep active */
297         int nodetype;                           /* Node type */
298         int switchtype;                         /* Type of switch to emulate */
299         int dialplan;                   /* Dialing plan */
300         int dchannel;                   /* What channel the dchannel is on */
301         int channels;                   /* Num of chans in span (31 or 24) */
302         int overlapdial;                /* In overlap dialing mode */
303         struct pri *pri;
304         int debug;
305         int fd;
306         int up;
307         int offset;
308         int span;
309         int chanmask[32];                       /* Channel status */
310         int resetting;
311         int resetchannel;
312         time_t lastreset;
313         struct zt_pvt *pvt[32]; /* Member channel pvt structs */
314         struct zt_channel *chan[32];    /* Channels on each line */
315 };
316
317
318 static struct zt_pri pris[NUM_SPANS];
319
320 static int pritype = PRI_CPE;
321
322 #if 0
323 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
324 #else
325 #define DEFAULT_PRI_DEBUG 0
326 #endif
327
328 static inline void pri_rel(struct zt_pri *pri)
329 {
330         ast_mutex_unlock(&pri->lock);
331 }
332
333 static int switchtype = PRI_SWITCH_NI2;
334 static int dialplan = PRI_NATIONAL_ISDN + 1;
335
336 #endif
337
338 #define SUB_REAL                0                       /* Active call */
339 #define SUB_CALLWAIT    1                       /* Call-Waiting call on hold */
340 #define SUB_THREEWAY    2                       /* Three-way call */
341
342
343 static struct zt_distRings drings;
344
345 struct distRingData {
346         int ring[3];
347 };
348 struct ringContextData {
349         char contextData[AST_MAX_EXTENSION];
350 };
351 struct zt_distRings {
352         struct distRingData ringnum[3];
353         struct ringContextData ringContext[3];
354 };
355
356 static char *subnames[] = {
357         "Real",
358         "Callwait",
359         "Threeway"
360 };
361
362 struct zt_subchannel {
363         int zfd;
364         struct ast_channel *owner;
365         int chan;
366         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
367         struct ast_frame f;             /* One frame for each channel.  How did this ever work before? */
368         int needringing;
369         int needbusy;
370         int needcongestion;
371         int needcallerid;
372         int needanswer;
373         int linear;
374         int inthreeway;
375         ZT_CONFINFO curconf;
376 };
377
378 #define CONF_USER_REAL          (1 << 0)
379 #define CONF_USER_THIRDCALL     (1 << 1)
380
381 #define MAX_SLAVES      4
382
383 static struct zt_pvt {
384         ast_mutex_t lock;
385         struct ast_channel *owner;      /* Our current active owner (if applicable) */
386                 /* Up to three channels can be associated with this call */
387                 
388         struct zt_subchannel sub_unused;        /* Just a safety precaution */
389         struct zt_subchannel subs[3];   /* Sub-channels */
390         struct zt_confinfo saveconf;    /* Saved conference info */
391
392         struct zt_pvt *slaves[MAX_SLAVES];      /* Slave to us (follows our conferencing) */
393         struct zt_pvt *master;  /* Master to us (we follow their conferencing) */
394         int inconference;               /* If our real should be in the conference */
395         
396         int sig;                                        /* Signalling style */
397         int radio;                              /* radio type */
398         int firstradio;                         /* first radio flag */
399         float rxgain;
400         float txgain;
401         int tonezone;                           /* tone zone for this chan, or -1 for default */
402         struct zt_pvt *next;                    /* Next channel in list */
403         struct zt_pvt *prev;                    /* Prev channel in list */
404
405         struct zt_distRings drings;
406         int usedistinctiveringdetection;
407
408         char context[AST_MAX_EXTENSION];
409         char defcontext[AST_MAX_EXTENSION];
410         char exten[AST_MAX_EXTENSION];
411         char language[MAX_LANGUAGE];
412         char musicclass[MAX_LANGUAGE];
413         char callerid[AST_MAX_EXTENSION];
414         char lastcallerid[AST_MAX_EXTENSION];
415         char *origcallerid;                     /* malloced original callerid */
416         char callwaitcid[AST_MAX_EXTENSION];
417         char rdnis[AST_MAX_EXTENSION];
418         char dnid[AST_MAX_EXTENSION];
419         unsigned int group;
420         int law;
421         int confno;                                     /* Our conference */
422         int confusers;                          /* Who is using our conference */
423         int propconfno;                         /* Propagated conference number */
424         unsigned int callgroup;
425         unsigned int pickupgroup;
426         int immediate;                          /* Answer before getting digits? */
427         int channel;                            /* Channel Number */
428         int span;                                       /* Span number */
429         int dialing;
430         int dialednone;
431         int use_callerid;                       /* Whether or not to use caller id on this channel */
432         int hidecallerid;
433         int callreturn;
434         int permhidecallerid;           /* Whether to hide our outgoing caller ID or not */
435         int restrictcid;                /* Whether restrict the callerid -> only send ANI */
436         int use_callingpres;            /* Whether to use the callingpres the calling switch sends */
437         int callingpres;                /* The value of callling presentation that we're going to use when placing a PRI call */
438         int callwaitingrepeat;          /* How many samples to wait before repeating call waiting */
439         int cidcwexpire;                        /* When to expire our muting for CID/CW */
440         unsigned char *cidspill;
441         int cidpos;
442         int cidlen;
443         int ringt;
444         int stripmsd;
445         int callwaiting;
446         int callwaitcas;
447         int callwaitrings;
448         int echocancel;
449         int echotraining;
450         int echocanbridged;
451         int echocanon;
452         int echobreak;
453         char echorest[10];
454         int permcallwaiting;
455         int callwaitingcallerid;
456         int threewaycalling;
457         int transfer;
458         int digital;
459         int outgoing;
460         int dnd;
461         int busydetect;
462         int busycount;
463         int callprogress;
464         struct timeval flashtime;       /* Last flash-hook time */
465         struct ast_dsp *dsp;
466         int cref;                                       /* Call reference number */
467         ZT_DIAL_OPERATION dop;
468         int destroy;
469         int ignoredtmf;                         
470         int inalarm;
471         char accountcode[20];           /* Account code */
472         int amaflags;                           /* AMA Flags */
473         char didtdd;                    /* flag to say its done it once */
474         struct tdd_state *tdd;          /* TDD flag */
475         int adsi;
476         int cancallforward;
477         char call_forward[AST_MAX_EXTENSION];
478         char mailbox[AST_MAX_EXTENSION];
479         char dialdest[256];
480         int onhooktime;
481         int msgstate;
482         
483         int confirmanswer;              /* Wait for '#' to confirm answer */
484         int distinctivering;    /* Which distinctivering to use */
485         int cidrings;                   /* Which ring to deliver CID on */
486         
487         int faxhandled;                 /* Has a fax tone already been handled? */
488         
489         char mate;                      /* flag to say its in MATE mode */
490         int pulsedial;          /* whether a pulse dial phone is detected */
491         int dtmfrelax;          /* whether to run in relaxed DTMF mode */
492         int fake_event;
493         int zaptrcallerid;      /* should we use the callerid from incoming call on zap transfer or not */
494 #ifdef ZAPATA_PRI
495         struct zt_pri *pri;
496         q931_call *call;
497         int isidlecall;
498         int resetting;
499         int prioffset;
500         int alreadyhungup;
501 #ifdef PRI_EVENT_PROCEEDING
502         int proceeding;
503 #endif
504         int setup_ack;          /* wheter we received SETUP_ACKNOWLEDGE or not */
505 #endif  
506 #ifdef ZAPATA_R2
507         int r2prot;
508         mfcr2_t *r2;
509         int hasr2call;
510         int r2blocked;
511         int sigchecked;
512 #endif  
513 } *iflist = NULL, *ifend = NULL;
514
515 struct zt_pvt *round_robin[32];
516
517 #ifdef ZAPATA_PRI
518 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
519 {
520         int res;
521         /* Grab the lock first */
522         do {
523             res = ast_mutex_trylock(&pri->lock);
524                 if (res) {
525                         ast_mutex_unlock(&pvt->lock);
526                         /* Release the lock and try again */
527                         usleep(1);
528                         ast_mutex_lock(&pvt->lock);
529                 }
530         } while(res);
531         /* Then break the select */
532         pthread_kill(pri->master, SIGURG);
533         return 0;
534 }
535 #endif
536
537 #define NUM_CADENCE_MAX 25
538 static int num_cadence = 4;
539 static int user_has_defined_cadences = 0;
540
541 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
542         { { 125, 125, 2000, 4000 } },                   /* Quick chirp followed by normal ring */
543         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /* British style ring */
544         { { 125, 125, 125, 125, 125, 4000 } },  /* Three short bursts */
545         { { 1000, 500, 2500, 5000 } },  /* Long ring */
546 };
547
548 int receivedRingT; /* Used to find out what ringtone we are on */
549
550 /* cidrings says in which pause to transmit the cid information, where the first pause
551  * is 1, the second pause is 2 and so on.
552  */
553
554 static int cidrings[NUM_CADENCE_MAX] = {
555         2,                                                                              /* Right after first long ring */
556         4,                                                                              /* Right after long part */
557         3,                                                                              /* After third chirp */
558         2,                                                                              /* Second spell */
559 };
560
561 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
562                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
563
564 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
565 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
566
567 #ifdef ZAPATA_PRI
568 /* translate between PRI causes and asterisk's */
569 static int hangup_pri2cause(int cause)
570 {
571         switch(cause) {
572                 case PRI_CAUSE_USER_BUSY:
573                         return AST_CAUSE_BUSY;
574                 case PRI_CAUSE_NORMAL_CLEARING:
575                         return AST_CAUSE_NORMAL;
576                 case PRI_CAUSE_NORMAL_CIRCUIT_CONGESTION:
577                 case PRI_CAUSE_REQUESTED_CHAN_UNAVAIL:
578                         return AST_CAUSE_CONGESTION;
579                 case PRI_CAUSE_UNALLOCATED:
580                 case PRI_CAUSE_NUMBER_CHANGED:
581                         return AST_CAUSE_UNALLOCATED;
582                 default:
583                         return AST_CAUSE_FAILURE;
584         }
585         /* never reached */
586         return 0;
587 }
588
589 /* translate between ast cause and PRI */
590 static int hangup_cause2pri(int cause)
591 {
592         switch(cause) {
593                 case AST_CAUSE_BUSY:
594                         return PRI_CAUSE_USER_BUSY;
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                         /* Select 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                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2072                         pri_rel(p->pri);
2073                 } else {
2074                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2075                         res= -1;
2076                 }
2077                 break;
2078 #endif
2079 #ifdef ZAPATA_R2
2080         case SIG_R2:
2081                 res = mfcr2_AnswerCall(p->r2, NULL);
2082                 if (res)
2083                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2084                 break;
2085 #endif                  
2086         case 0:
2087                 ast_mutex_unlock(&p->lock);
2088                 return 0;
2089         default:
2090                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2091                 res = -1;
2092         }
2093         ast_mutex_unlock(&p->lock);
2094         return res;
2095 }
2096
2097 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2098 {
2099 char    *cp;
2100 int     x;
2101
2102         struct zt_pvt *p = chan->pvt->pvt;
2103
2104         
2105         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2106                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2107            {
2108                 errno = ENOSYS;
2109                 return -1;
2110            }
2111         cp = (char *)data;
2112         if ((!cp) || (datalen < 1))
2113            {
2114                 errno = EINVAL;
2115                 return -1;
2116            }
2117         switch(option) {
2118             case AST_OPTION_TONE_VERIFY:
2119                 if (!p->dsp)
2120                         break;
2121                 switch(*cp) {
2122                     case 1:
2123                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2124                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2125                         break;
2126                     case 2:
2127                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2128                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2129                         break;
2130                     default:
2131                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2132                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2133                         break;
2134                 }
2135                 break;
2136             case AST_OPTION_TDD:  /* turn on or off TDD */
2137                 if (!*cp) { /* turn it off */
2138                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2139                         if (p->tdd) tdd_free(p->tdd);
2140                         p->tdd = 0;
2141                         p->mate = 0;
2142                         break;
2143                 }
2144                 if (*cp == 2)
2145                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2146                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2147                 p->mate = 0;
2148                 zt_disable_ec(p);
2149                 /* otherwise, turn it on */
2150                 if (!p->didtdd) { /* if havent done it yet */
2151                         unsigned char mybuf[41000],*buf;
2152                         int size,res,fd,len;
2153                         int index;
2154                         fd_set wfds,efds;
2155                         buf = mybuf;
2156                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2157                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2158                         len = 40000;
2159                         index = zt_get_index(chan, p, 0);
2160                         if (index < 0) {
2161                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2162                                 return -1;
2163                         }
2164                         fd = p->subs[index].zfd;
2165                         while(len) {
2166                                 if (ast_check_hangup(chan)) return -1;
2167                                 size = len;
2168                                 if (size > READ_SIZE)
2169                                         size = READ_SIZE;
2170                                 FD_ZERO(&wfds);
2171                                 FD_ZERO(&efds);
2172                                 FD_SET(fd,&wfds);
2173                                 FD_SET(fd,&efds);                       
2174                                 res = ast_select(fd + 1,NULL,&wfds,&efds,NULL);
2175                                 if (!res) {
2176                                         ast_log(LOG_DEBUG, "select (for write) ret. 0 on channel %d\n", p->channel);
2177                                         continue;
2178                                 }
2179                                   /* if got exception */
2180                                 if (FD_ISSET(fd,&efds)) return -1;
2181                                 if (!FD_ISSET(fd,&wfds)) {
2182                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2183                                         continue;
2184                                 }
2185                                 res = write(fd, buf, size);
2186                                 if (res != size) {
2187                                         if (res == -1) return -1;
2188                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2189                                         break;
2190                                 }
2191                                 len -= size;
2192                                 buf += size;
2193                         }
2194                         p->didtdd = 1; /* set to have done it now */            
2195                 }
2196                 if (*cp == 2) { /* Mate mode */
2197                         if (p->tdd) tdd_free(p->tdd);
2198                         p->tdd = 0;
2199                         p->mate = 1;
2200                         break;
2201                         }               
2202                 if (!p->tdd) { /* if we dont have one yet */
2203                         p->tdd = tdd_new(); /* allocate one */
2204                 }               
2205                 break;
2206             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2207                 if (!*cp)
2208                 {               
2209                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2210                         x = 0;
2211                 }
2212                 else
2213                 {               
2214                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2215                         x = 1;
2216                 }
2217                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2218                 break;
2219             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2220                 if (!*cp)
2221                 {               
2222                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2223                         x = 0;
2224                         zt_disable_ec(p);
2225                 }
2226                 else
2227                 {               
2228                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2229                         x = 1;
2230                 }
2231                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2232                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2233                 break;
2234         }
2235         errno = 0;
2236         return 0;
2237 }
2238
2239 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2240 {
2241         /* Unlink a specific slave or all slaves/masters from a given master */
2242         int x;
2243         int hasslaves;
2244         if (!master)
2245                 return;
2246         if (needlock) {
2247                 ast_mutex_lock(&master->lock);
2248                 if (slave) {
2249                         while(ast_mutex_trylock(&slave->lock)) {
2250                                 ast_mutex_unlock(&master->lock);
2251                                 usleep(1);
2252                                 ast_mutex_lock(&master->lock);
2253                         }
2254                 }
2255         }
2256         hasslaves = 0;
2257         for (x=0;x<MAX_SLAVES;x++) {
2258                 if (master->slaves[x]) {
2259                         if (!slave || (master->slaves[x] == slave)) {
2260                                 /* Take slave out of the conference */
2261                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2262                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2263                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2264                                 master->slaves[x]->master = NULL;
2265                                 master->slaves[x] = NULL;
2266                         } else
2267                                 hasslaves = 1;
2268                 }
2269                 if (!hasslaves)
2270                         master->inconference = 0;
2271         }
2272         if (!slave) {
2273                 if (master->master) {
2274                         /* Take master out of the conference */
2275                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2276                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2277                         hasslaves = 0;
2278                         for (x=0;x<MAX_SLAVES;x++) {
2279                                 if (master->master->slaves[x] == master)
2280                                         master->master->slaves[x] = NULL;
2281                                 else if (master->master->slaves[x])
2282                                         hasslaves = 1;
2283                         }
2284                         if (!hasslaves)
2285                                 master->master->inconference = 0;
2286                 }
2287                 master->master = NULL;
2288         }
2289         update_conf(master);
2290         if (needlock) {
2291                 if (slave)
2292                         ast_mutex_unlock(&slave->lock);
2293                 ast_mutex_unlock(&master->lock);
2294         }
2295 }
2296
2297 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2298         int x;
2299         if (!slave || !master) {
2300                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2301                 return;
2302         }
2303         for (x=0;x<MAX_SLAVES;x++) {
2304                 if (!master->slaves[x]) {
2305                         master->slaves[x] = slave;
2306                         break;
2307                 }
2308         }
2309         if (x >= MAX_SLAVES) {
2310                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2311                 master->slaves[MAX_SLAVES - 1] = slave;
2312         }
2313         if (slave->master) 
2314                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2315         slave->master = master;
2316         
2317         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2318 }
2319
2320 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2321 {
2322         struct ast_channel *who = NULL, *cs[3];
2323         struct zt_pvt *p0, *p1, *op0, *op1;
2324         struct zt_pvt *master=NULL, *slave=NULL;
2325         struct ast_frame *f;
2326         int to;
2327         int inconf = 0;
2328         int nothingok = 0;
2329         int ofd1, ofd2;
2330         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2331         int os1 = -1, os2 = -1;
2332         struct ast_channel *oc1, *oc2;
2333
2334         /* if need DTMF, cant native bridge */
2335         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2336                 return -2;
2337                 
2338         ast_mutex_lock(&c0->lock);
2339         ast_mutex_lock(&c1->lock);
2340
2341         p0 = c0->pvt->pvt;
2342         p1 = c1->pvt->pvt;
2343         /* cant do pseudo-channels here */
2344         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2345                 ast_mutex_unlock(&c0->lock);
2346                 ast_mutex_unlock(&c1->lock);
2347                 return -2;
2348         }
2349
2350         op0 = p0 = c0->pvt->pvt;
2351         op1 = p1 = c1->pvt->pvt;
2352         ofd1 = c0->fds[0];
2353         ofd2 = c1->fds[0];
2354         oi1 = zt_get_index(c0, p0, 0);
2355         oi2 = zt_get_index(c1, p1, 0);
2356         oc1 = p0->owner;
2357         oc2 = p1->owner;
2358         if ((oi1 < 0) || (oi2 < 0)) {
2359                 ast_mutex_unlock(&c0->lock);
2360                 ast_mutex_unlock(&c1->lock);
2361                 return -1;
2362         }
2363
2364
2365
2366         ast_mutex_lock(&p0->lock);
2367         if (ast_mutex_trylock(&p1->lock)) {
2368                 /* Don't block, due to potential for deadlock */
2369                 ast_mutex_unlock(&p0->lock);
2370                 ast_mutex_unlock(&c0->lock);
2371                 ast_mutex_unlock(&c1->lock);
2372                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2373                 return -3;
2374         }
2375         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2376                 if (!p0->owner || !p1->owner) {
2377                         /* Currently unowned -- Do nothing.  */
2378                         nothingok = 1;
2379                 } else {
2380                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2381                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2382                                 master = p0;
2383                                 slave = p1;
2384                                 inconf = 1;
2385                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2386                                 master = p1;
2387                                 slave = p0;
2388                                 inconf = 1;
2389                         } else {
2390                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2391                                 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,
2392                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2393                         }
2394                 }
2395         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2396                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2397                         master = p1;
2398                         slave = p0;
2399                 } else {
2400                         nothingok = 1;
2401                 }
2402         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2403                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2404                         master = p0;
2405                         slave = p1;
2406                 } else {
2407                         nothingok  = 1;
2408                 }
2409         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2410                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2411                    don't put us in anything */
2412                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2413                         master = p1;
2414                         slave = p0;
2415                 } else {
2416                         nothingok = 1;
2417                 }
2418         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2419                 /* Same as previous */
2420                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2421                         master = p0;
2422                         slave = p1;
2423                 } else {
2424                         nothingok = 1;
2425                 }
2426         }
2427         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2428                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2429         if (master && slave) {
2430                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2431                    in an active threeway call with a channel that is ringing, we should
2432                    indicate ringing. */
2433                 if ((oi2 == SUB_THREEWAY) && 
2434                         p1->subs[SUB_THREEWAY].inthreeway && 
2435                         p1->subs[SUB_REAL].owner && 
2436                         p1->subs[SUB_REAL].inthreeway && 
2437                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2438                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2439                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2440                                 os2 = p1->subs[SUB_REAL].owner->_state;
2441                 } else {
2442                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2443                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2444                 }
2445                 if ((oi1 == SUB_THREEWAY) && 
2446                         p0->subs[SUB_THREEWAY].inthreeway && 
2447                         p0->subs[SUB_REAL].owner && 
2448                         p0->subs[SUB_REAL].inthreeway && 
2449                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2450                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2451                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2452                                 os1 = p0->subs[SUB_REAL].owner->_state;
2453                 } else {
2454                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2455                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2456                 }
2457                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2458                         if (!p0->echocanbridged || !p1->echocanbridged) {
2459                                 /* Disable echo cancellation if appropriate */
2460                                 zt_disable_ec(p0);
2461                                 zt_disable_ec(p1);
2462                         }
2463                 }
2464                 zt_link(slave, master);
2465                 master->inconference = inconf;
2466         } else if (!nothingok)
2467                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2468
2469         update_conf(p0);
2470         update_conf(p1);
2471         t1 = p0->subs[SUB_REAL].inthreeway;
2472         t2 = p1->subs[SUB_REAL].inthreeway;
2473
2474         ast_mutex_unlock(&p0->lock);
2475         ast_mutex_unlock(&p1->lock);
2476
2477         ast_mutex_unlock(&c0->lock);
2478         ast_mutex_unlock(&c1->lock);
2479
2480         /* Native bridge failed */
2481         if ((!master || !slave) && !nothingok) {
2482                 if (op0 == p0)
2483                         zt_enable_ec(p0);
2484                 if (op1 == p1)
2485                         zt_enable_ec(p1);
2486                 return -1;
2487         }
2488         
2489         cs[0] = c0;
2490         cs[1] = c1;
2491         cs[2] = NULL;
2492         for (;;) {
2493                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2494                    and then balking if anything is wrong */
2495                 ast_mutex_lock(&c0->lock);
2496                 ast_mutex_lock(&c1->lock);
2497                 p0 = c0->pvt->pvt;
2498                 p1 = c1->pvt->pvt;
2499                 if (op0 == p0)
2500                         i1 = zt_get_index(c0, p0, 1);
2501                 if (op1 == p1)
2502                         i2 = zt_get_index(c1, p1, 1);
2503                 ast_mutex_unlock(&c0->lock);
2504                 ast_mutex_unlock(&c1->lock);
2505                 if ((op0 != p0) || (op1 != p1) || 
2506                     (ofd1 != c0->fds[0]) || 
2507                         (ofd2 != c1->fds[0]) ||
2508                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2509                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2510                     (oc1 != p0->owner) || 
2511                         (oc2 != p1->owner) ||
2512                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2513                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2514                         (oi1 != i1) ||
2515                         (oi2 != i2)) {
2516                         if (slave && master)
2517                                 zt_unlink(slave, master, 1);
2518                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2519                                                                         op0->channel, oi1, op1->channel, oi2);
2520                         if (op0 == p0)
2521                                 zt_enable_ec(p0);
2522                         if (op1 == p1)
2523                                 zt_enable_ec(p1);
2524                         return -3;
2525                 }
2526                 to = -1;
2527                 who = ast_waitfor_n(cs, 2, &to);
2528                 if (!who) {
2529                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2530                         continue;
2531                 }
2532                 if (who->pvt->pvt == op0) 
2533                         op0->ignoredtmf = 1;
2534                 else if (who->pvt->pvt == op1)
2535                         op1->ignoredtmf = 1;
2536                 f = ast_read(who);
2537                 if (who->pvt->pvt == op0) 
2538                         op0->ignoredtmf = 0;
2539                 else if (who->pvt->pvt == op1)
2540                         op1->ignoredtmf = 0;
2541                 if (!f) {
2542                         *fo = NULL;
2543                         *rc = who;
2544                         if (slave && master)
2545                                 zt_unlink(slave, master, 1);
2546                         if (op0 == p0)
2547                                 zt_enable_ec(p0);
2548                         if (op1 == p1)
2549                                 zt_enable_ec(p1);
2550                         return 0;
2551                 }
2552                 if (f->frametype == AST_FRAME_DTMF) {
2553                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2554                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2555                                 *fo = f;
2556                                 *rc = who;
2557                                 if (slave && master)
2558                                         zt_unlink(slave, master, 1);
2559                                 return 0;
2560                         } else if ((who == c0) && p0->pulsedial) {
2561                                 ast_write(c1, f);
2562                         } else if ((who == c1) && p1->pulsedial) {
2563                                 ast_write(c0, f);
2564                         }
2565                 }
2566                 ast_frfree(f);
2567
2568                 /* Swap who gets priority */
2569                 cs[2] = cs[0];
2570                 cs[0] = cs[1];
2571                 cs[1] = cs[2];
2572         }
2573 }
2574
2575 static int zt_indicate(struct ast_channel *chan, int condition);
2576
2577 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2578 {
2579         struct zt_pvt *p = newchan->pvt->pvt;
2580         int x;
2581         ast_mutex_lock(&p->lock);
2582         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2583         if (p->owner == oldchan)
2584                 p->owner = newchan;
2585         for (x=0;x<3;x++)
2586                 if (p->subs[x].owner == oldchan) {
2587                         if (!x)
2588                                 zt_unlink(NULL, p, 0);
2589                         p->subs[x].owner = newchan;
2590                 }
2591         if (newchan->_state == AST_STATE_RINGING) 
2592                 zt_indicate(newchan, AST_CONTROL_RINGING);
2593         update_conf(p);
2594         ast_mutex_unlock(&p->lock);
2595         return 0;
2596 }
2597
2598 static int zt_ring_phone(struct zt_pvt *p)
2599 {
2600         int x;
2601         int res;
2602         /* Make sure our transmit state is on hook */
2603         x = 0;
2604         x = ZT_ONHOOK;
2605         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2606         do {
2607                 x = ZT_RING;
2608                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2609 #if 0
2610                 printf("Res: %d, error: %s\n", res, strerror(errno));
2611 #endif                                          
2612                 if (res) {
2613                         switch(errno) {
2614                         case EBUSY:
2615                         case EINTR:
2616                                 /* Wait just in case */
2617                                 usleep(10000);
2618                                 continue;
2619                         case EINPROGRESS:
2620                                 res = 0;
2621                                 break;
2622                         default:
2623                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2624                                 res = 0;
2625                         }
2626                 }
2627         } while (res);
2628         return res;
2629 }
2630
2631 static void *ss_thread(void *data);
2632
2633 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2634
2635 static int attempt_transfer(struct zt_pvt *p)
2636 {
2637         /* In order to transfer, we need at least one of the channels to
2638            actually be in a call bridge.  We can't conference two applications
2639            together (but then, why would we want to?) */
2640         if (p->subs[SUB_REAL].owner->bridge) {
2641                 /* The three-way person we're about to transfer to could still be in MOH, so
2642                    stop if now if appropriate */
2643                 if (p->subs[SUB_THREEWAY].owner->bridge)
2644                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2645                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2646                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2647                 }
2648                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2649                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2650                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2651                         return -1;
2652                 }
2653                 /* Orphan the channel */
2654                 unalloc_sub(p, SUB_THREEWAY);
2655         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2656                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2657                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2658                 }
2659                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2660                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2661                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2662                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2663                         return -1;
2664                 }
2665                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2666                 unalloc_sub(p, SUB_THREEWAY);
2667                 /* Tell the caller not to hangup */
2668                 return 1;
2669         } else {
2670                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2671                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2672                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2673         }
2674         return 0;
2675 }
2676
2677 #ifdef ZAPATA_R2
2678 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2679 {
2680         struct ast_frame *f;
2681         f = &p->subs[index].f;
2682         if (!p->r2) {
2683                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2684                 return NULL;
2685         }
2686         switch(e->e) {
2687         case MFCR2_EVENT_BLOCKED:
2688                 if (option_verbose > 2)
2689                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2690                 break;
2691         case MFCR2_EVENT_UNBLOCKED:
2692                 if (option_verbose > 2)
2693                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2694                 break;
2695         case MFCR2_EVENT_CONFIG_ERR:
2696                 if (option_verbose > 2)
2697                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2698                 break;
2699         case MFCR2_EVENT_RING:
2700                 if (option_verbose > 2)
2701                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2702                 break;
2703         case MFCR2_EVENT_HANGUP:
2704                 if (option_verbose > 2)
2705                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2706                 break;
2707         case MFCR2_EVENT_RINGING:
2708                 if (option_verbose > 2)
2709                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2710                 break;
2711         case MFCR2_EVENT_ANSWER:
2712                 if (option_verbose > 2)
2713                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2714                 break;
2715         case MFCR2_EVENT_HANGUP_ACK:
2716                 if (option_verbose > 2)
2717                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2718                 break;
2719         case MFCR2_EVENT_IDLE:
2720                 if (option_verbose > 2)
2721                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2722                 break;
2723         default:
2724                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2725                 break;
2726         }
2727         return f;
2728 }
2729
2730 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2731 {
2732         int x;
2733         int res;
2734         mfcr2_event_t *e;
2735         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2736         if (res) {
2737                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2738                 return NULL;
2739         }
2740         if (!p->r2) {
2741                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2742                 return NULL;
2743         }
2744         e = mfcr2_cas_signaling_event(p->r2, x);
2745         return e;
2746 }
2747 #endif
2748
2749 static int check_for_conference(struct zt_pvt *p)
2750 {
2751         ZT_CONFINFO ci;
2752         /* Fine if we already have a master, etc */
2753         if (p->master || (p->confno > -1))
2754                 return 0;
2755         memset(&ci, 0, sizeof(ci));
2756         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2757                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2758                 return 0;
2759         }
2760         /* If we have no master and don't have a confno, then 
2761            if we're in a conference, it's probably a MeetMe room or
2762            some such, so don't let us 3-way out! */
2763         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
2764                 if (option_verbose > 2) 
2765                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2766                 return 1;
2767         }
2768         return 0;
2769 }
2770
2771 static int get_alarms(struct zt_pvt *p)
2772 {
2773         int res;
2774         ZT_SPANINFO zi;
2775         memset(&zi, 0, sizeof(zi));
2776         zi.spanno = p->span;
2777         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2778         if (res < 0) {
2779                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2780                 return 0;
2781         }
2782         return zi.alarms;
2783 }
2784                         
2785 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2786 {
2787         int res,x;
2788         int index;
2789         char *c;
2790         struct zt_pvt *p = ast->pvt->pvt;
2791         pthread_t threadid;
2792         pthread_attr_t attr;
2793         struct ast_channel *chan;
2794         pthread_attr_init(&attr);
2795         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2796         index = zt_get_index(ast, p, 0);
2797         p->subs[index].f.frametype = AST_FRAME_NULL;
2798         p->subs[index].f.datalen = 0;
2799         p->subs[index].f.samples = 0;
2800         p->subs[index].f.mallocd = 0;
2801         p->subs[index].f.offset = 0;
2802         p->subs[index].f.src = "zt_handle_event";
2803         p->subs[index].f.data = NULL;
2804         if (index < 0)
2805                 return &p->subs[index].f;
2806         if (p->fake_event) {
2807                 res = p->fake_event;
2808                 p->fake_event = 0;
2809         } else
2810                 res = zt_get_event(p->subs[index].zfd);
2811         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
2812         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFDIGIT)) {
2813                 if (res & ZT_EVENT_PULSEDIGIT)
2814                         p->pulsedial = 1;
2815                 else
2816                         p->pulsedial = 0;
2817                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
2818                 p->subs[index].f.frametype = AST_FRAME_DTMF;
2819                 p->subs[index].f.subclass = res & 0xff;
2820                 /* Return the captured digit */
2821                 return &p->subs[index].f;
2822         }
2823         switch(res) {
2824                 case ZT_EVENT_BITSCHANGED:
2825                         if (p->sig == SIG_R2) {
2826 #ifdef ZAPATA_R2
2827                                 struct ast_frame  *f = &p->subs[index].f;
2828                                 mfcr2_event_t *e;
2829                                 e = r2_get_event_bits(p);
2830                                 if (e)
2831                                         f = handle_r2_event(p, e, index);
2832                                 return f;
2833 #else                           
2834                                 break;
2835 #endif
2836                         }
2837                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
2838                 case ZT_EVENT_PULSE_START:
2839                         /* Stop tone if there's a pulse start and the PBX isn't started */
2840                         if (!ast->pbx)
2841                                 tone_zone_play_tone(p->subs[index].zfd, -1);
2842                         break;  
2843                 case ZT_EVENT_DIALCOMPLETE:
2844                         if (p->inalarm) break;
2845                         if (p->radio) break;
2846                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
2847                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
2848                                 return NULL;
2849                         }
2850                         if (!x) { /* if not still dialing in driver */
2851                                 zt_enable_ec(p);
2852                                 if (p->echobreak) {
2853                                         zt_train_ec(p);
2854                                         strcpy(p->dop.dialstr, p->echorest);
2855                                         p->dop.op = ZT_DIAL_OP_REPLACE;
2856                                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2857                                         p->echobreak = 0;
2858                                 } else {
2859                                         p->dialing = 0;
2860                                         if (p->sig == SIG_E911) {
2861                                                 /* if thru with dialing after offhook */
2862                                                 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2863                                                         ast_setstate(ast, AST_STATE_UP);
2864                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2865                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2866                                                         break;
2867                                                 } else { /* if to state wait for offhook to dial rest */
2868                                                         /* we now wait for off hook */
2869                                                         ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2870                                                 }
2871                                         }
2872                                         if (ast->_state == AST_STATE_DIALING) {
2873                                                 if (p->callprogress && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
2874                                                         ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
2875                                                 } 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)))) {
2876                                                         ast_setstate(ast, AST_STATE_RINGING);
2877                                                 } else {
2878                                                         ast_setstate(ast, AST_STATE_UP);
2879                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2880                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2881                                                 }
2882                                         }
2883                                 }
2884                         }
2885                         break;
2886                 case ZT_EVENT_ALARM:
2887 #ifdef ZAPATA_PRI
2888 #ifdef PRI_DESTROYCALL
2889                         if (p->call) {
2890                                 if (p->pri && p->pri->pri) {
2891                                         pri_hangup(p->pri->pri, p->call, -1);
2892                                         pri_destroycall(p->pri->pri, p->call);
2893                                 } else
2894                                         ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2895                         }
2896                         if (p->owner)
2897                                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2898                         p->call = NULL;
2899 #else
2900 #error Please "cvs update" and recompile libpri
2901 #endif
2902 #endif
2903                         p->inalarm = 1;
2904                         res = get_alarms(p);
2905                         ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
2906                         manager_event(EVENT_FLAG_SYSTEM, "Alarm",
2907                                                                 "Alarm: %s\r\n"
2908                                                                 "Channel: %d\r\n",
2909                                                                 alarm2str(res), p->channel);
2910                         /* fall through intentionally */
2911                 case ZT_EVENT_ONHOOK:
2912                         if (p->radio)
2913                         {
2914                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2915                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
2916                                 break;
2917                         }
2918                         switch(p->sig) {
2919                         case SIG_FXOLS:
2920                         case SIG_FXOGS:
2921                         case SIG_FXOKS:
2922                                 p->onhooktime = time(NULL);
2923                                 p->msgstate = -1;
2924                                 /* Check for some special conditions regarding call waiting */
2925                                 if (index == SUB_REAL) {
2926                                         /* The normal line was hung up */
2927                                         if (p->subs[SUB_CALLWAIT].owner) {
2928                                                 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2929                                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2930                                                 if (option_verbose > 2) 
2931                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2932                                                 unalloc_sub(p, SUB_CALLWAIT);   
2933 #if 0
2934                                                 p->subs[index].needanswer = 0;
2935                                                 p->subs[index].needringing = 0;
2936 #endif                                          
2937                                                 p->callwaitingrepeat = 0;
2938                                                 p->cidcwexpire = 0;
2939                                                 p->owner = NULL;
2940                                                 zt_ring_phone(p);
2941                                         } else if (p->subs[SUB_THREEWAY].owner) {
2942                                                 struct timeval tv;
2943                                                 unsigned int mssinceflash;
2944                                                 gettimeofday(&tv, NULL);
2945                                                 mssinceflash = (tv.tv_sec - p->flashtime.tv_sec) * 1000 + (tv.tv_usec - p->flashtime.tv_usec) / 1000;
2946                                                 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
2947                                                 if (mssinceflash < MIN_MS_SINCE_FLASH) {
2948                                                         /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
2949                                                            hanging up.  Hangup both channels now */
2950                                                         if (p->subs[SUB_THREEWAY].owner)
2951                                                                 ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
2952                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2953           &n