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