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