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