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