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