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