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