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