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