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