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