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