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