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