Fix the dependancy on libpri in zt_digit
[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         x = 1;
1444         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
1445
1446         restore_gains(p);
1447         
1448         if (p->dsp)
1449                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
1450
1451         x = 0;
1452         zt_confmute(p, 0);
1453
1454         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1455                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
1456         p->ignoredtmf = 0;
1457         
1458         if (index > -1) {
1459                 /* Real channel, do some fixup */
1460                 p->subs[index].owner = NULL;
1461                 p->subs[index].needanswer = 0;
1462                 p->subs[index].needringing = 0;
1463                 p->subs[index].linear = 0;
1464                 p->subs[index].needcallerid = 0;
1465                 zt_setlinear(p->subs[index].zfd, 0);
1466                 if (index == SUB_REAL) {
1467                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
1468                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
1469                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
1470                                         /* We had flipped over to answer a callwait and now it's gone */
1471                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
1472                                         /* Move to the call-wait, but un-own us until they flip back. */
1473                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1474                                         unalloc_sub(p, SUB_CALLWAIT);
1475                                         p->owner = NULL;
1476                                 } else {
1477                                         /* The three way hung up, but we still have a call wait */
1478                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1479                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
1480                                         unalloc_sub(p, SUB_THREEWAY);
1481                                         if (p->subs[SUB_REAL].inthreeway) {
1482                                                 /* This was part of a three way call.  Immediately make way for
1483                                                    another call */
1484                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1485                                                 p->owner = p->subs[SUB_REAL].owner;
1486                                         } else {
1487                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1488                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1489                                                 p->owner = NULL;
1490                                         }
1491                                         p->subs[SUB_REAL].inthreeway = 0;
1492                                 }
1493                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
1494                                 /* Move to the call-wait and switch back to them. */
1495                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1496                                 unalloc_sub(p, SUB_CALLWAIT);
1497                                 p->owner = p->subs[SUB_REAL].owner;
1498                                 if (p->subs[SUB_REAL].owner->bridge)
1499                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
1500                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
1501                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
1502                                 unalloc_sub(p, SUB_THREEWAY);
1503                                 if (p->subs[SUB_REAL].inthreeway) {
1504                                         /* This was part of a three way call.  Immediately make way for
1505                                            another call */
1506                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1507                                         p->owner = p->subs[SUB_REAL].owner;
1508                                 } else {
1509                                         /* This call hasn't been completed yet...  Set owner to NULL */
1510                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1511                                         p->owner = NULL;
1512                                 }
1513                                 p->subs[SUB_REAL].inthreeway = 0;
1514                         }
1515                 } else if (index == SUB_CALLWAIT) {
1516                         /* Ditch the holding callwait call, and immediately make it availabe */
1517                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1518                                 /* This is actually part of a three way, placed on hold.  Place the third part
1519                                    on music on hold now */
1520                                 if (p->subs[SUB_THREEWAY].owner && p->subs[SUB_THREEWAY].owner->bridge)
1521                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
1522                                 p->subs[SUB_THREEWAY].inthreeway = 0;
1523                                 /* Make it the call wait now */
1524                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
1525                                 unalloc_sub(p, SUB_THREEWAY);
1526                         } else
1527                                 unalloc_sub(p, SUB_CALLWAIT);
1528                 } else if (index == SUB_THREEWAY) {
1529                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1530                                 /* The other party of the three way call is currently in a call-wait state.
1531                                    Start music on hold for them, and take the main guy out of the third call */
1532                                 if (p->subs[SUB_CALLWAIT].owner && p->subs[SUB_CALLWAIT].owner->bridge)
1533                                         ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
1534                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
1535                         }
1536                         p->subs[SUB_REAL].inthreeway = 0;
1537                         /* If this was part of a three way call index, let us make
1538                            another three way call */
1539                         unalloc_sub(p, SUB_THREEWAY);
1540                 } else {
1541                         /* This wasn't any sort of call, but how are we an index? */
1542                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1543                 }
1544         }
1545
1546
1547         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
1548                 p->owner = NULL;
1549                 p->ringt = 0;
1550                 p->distinctivering = 0;
1551                 p->confirmanswer = 0;
1552                 p->cidrings = 1;
1553                 p->outgoing = 0;
1554                 p->digital = 0;
1555                 p->faxhandled = 0;
1556                 p->pulsedial = 0;
1557                 p->onhooktime = time(NULL);
1558                 if (p->dsp) {
1559                         ast_dsp_free(p->dsp);
1560                         p->dsp = NULL;
1561                 }
1562                 law = ZT_LAW_DEFAULT;
1563                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
1564                 if (res < 0) 
1565                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
1566                 /* Perform low level hangup if no owner left */
1567 #ifdef ZAPATA_PRI
1568                 if (p->sig == SIG_PRI) {
1569                         if (p->call) {
1570                                 if (!pri_grab(p->pri)) {
1571                                         res = pri_disconnect(p->pri->pri, p->call, PRI_CAUSE_NORMAL_CLEARING);
1572                                         if (p->alreadyhungup) {
1573                                                 p->call = NULL;
1574                                                 p->alreadyhungup = 0;
1575                                         }
1576                                         if (res < 0) 
1577                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
1578                                         pri_rel(p->pri);                        
1579                                 } else {
1580                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1581                                         res = -1;
1582                                 }
1583                         } else
1584                                 res = 0;
1585
1586                 } else 
1587 #endif
1588 #ifdef ZAPATA_R2
1589                 if (p->sig == SIG_R2) {
1590                         if (p->hasr2call) {
1591                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
1592                                 p->hasr2call = 0;
1593                                 res = 0;
1594                         } else
1595                                 res = 0;
1596
1597                 } else 
1598 #endif
1599                 if (p->sig)
1600                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
1601                 if (res < 0) {
1602                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1603                 }
1604                 switch(p->sig) {
1605                 case SIG_FXOGS:
1606                 case SIG_FXOLS:
1607                 case SIG_FXOKS:
1608                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
1609                         if (!res) {
1610 #if 0
1611                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
1612 #endif
1613                                 /* If they're off hook, try playing congestion */
1614                                 if (par.rxisoffhook)
1615                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
1616                                 else
1617                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1618                         }
1619                         break;
1620                 default:
1621                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1622                 }
1623                 if (p->cidspill)
1624                         free(p->cidspill);
1625                 if (p->sig)
1626                         zt_disable_ec(p);
1627                 x = 0;
1628                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1629                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1630                 p->didtdd = 0;
1631                 p->cidspill = NULL;
1632                 p->callwaitcas = 0;
1633                 p->callwaiting = p->permcallwaiting;
1634                 p->hidecallerid = p->permhidecallerid;
1635                 p->dialing = 0;
1636                 strcpy(p->rdnis, "");
1637                 update_conf(p);
1638                 restart_monitor();
1639         }
1640
1641
1642         p->callwaitingrepeat = 0;
1643         p->cidcwexpire = 0;
1644         ast->pvt->pvt = NULL;
1645         ast_setstate(ast, AST_STATE_DOWN);
1646         ast_pthread_mutex_unlock(&p->lock);
1647         ast_pthread_mutex_lock(&usecnt_lock);
1648         usecnt--;
1649         if (usecnt < 0) 
1650                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1651         ast_pthread_mutex_unlock(&usecnt_lock);
1652         ast_update_use_count();
1653         if (option_verbose > 2) 
1654                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
1655
1656         ast_pthread_mutex_lock(&iflock);
1657         tmp = iflist;
1658         prev = NULL;
1659         if (p->destroy) {
1660                 while (tmp) {
1661                         if (tmp == p) {
1662                                 destroy_channel(prev, tmp, 0);
1663                                 break;
1664                         } else {
1665                                 prev = tmp;
1666                                 tmp = tmp->next;
1667                         }
1668                 }
1669         }
1670         ast_pthread_mutex_unlock(&iflock);
1671         return 0;
1672 }
1673
1674 static int zt_answer(struct ast_channel *ast)
1675 {
1676         struct zt_pvt *p = ast->pvt->pvt;
1677         int res=0;
1678         int index;
1679         int oldstate = ast->_state;
1680         ast_setstate(ast, AST_STATE_UP);
1681         index = zt_get_index(ast, p, 0);
1682         if (index < 0)
1683                 index = SUB_REAL;
1684         /* nothing to do if a radio channel */
1685         if (p->radio)
1686                 return 0;
1687         switch(p->sig) {
1688         case SIG_FXSLS:
1689         case SIG_FXSGS:
1690         case SIG_FXSKS:
1691                 p->ringt = 0;
1692                 /* Fall through */
1693         case SIG_EM:
1694         case SIG_EMWINK:
1695         case SIG_FEATD:
1696         case SIG_FEATDMF:
1697         case SIG_FEATB:
1698         case SIG_SF:
1699         case SIG_SFWINK:
1700         case SIG_SF_FEATD:
1701         case SIG_SF_FEATDMF:
1702         case SIG_SF_FEATB:
1703         case SIG_FXOLS:
1704         case SIG_FXOGS:
1705         case SIG_FXOKS:
1706                 /* Pick up the line */
1707                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
1708                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
1709                 tone_zone_play_tone(p->subs[index].zfd, -1);
1710                 p->dialing = 0;
1711                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
1712                         if (oldstate == AST_STATE_RINGING) {
1713                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
1714                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
1715                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
1716                                 p->owner = p->subs[SUB_REAL].owner;
1717                         }
1718                 }
1719                 break;
1720 #ifdef ZAPATA_PRI
1721         case SIG_PRI:
1722                 /* Send a pri acknowledge */
1723                 if (!pri_grab(p->pri)) {
1724                         res = pri_answer(p->pri->pri, p->call, 0, 1);
1725                         pri_rel(p->pri);
1726                 } else {
1727                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1728                         res= -1;
1729                 }
1730                 break;
1731 #endif
1732 #ifdef ZAPATA_R2
1733         case SIG_R2:
1734                 res = mfcr2_AnswerCall(p->r2, NULL);
1735                 if (res)
1736                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
1737                 break;
1738 #endif                  
1739         case 0:
1740                 return 0;
1741         default:
1742                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1743                 return -1;
1744         }
1745         return res;
1746 }
1747
1748 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
1749 {
1750 char    *cp;
1751 int     x;
1752
1753         struct zt_pvt *p = chan->pvt->pvt;
1754
1755         
1756         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
1757                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
1758            {
1759                 errno = ENOSYS;
1760                 return -1;
1761            }
1762         cp = (char *)data;
1763         if ((!cp) || (datalen < 1))
1764            {
1765                 errno = EINVAL;
1766                 return -1;
1767            }
1768         switch(option) {
1769             case AST_OPTION_TONE_VERIFY:
1770                 if (!p->dsp)
1771                         break;
1772                 switch(*cp) {
1773                     case 1:
1774                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
1775                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
1776                         break;
1777                     case 2:
1778                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
1779                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
1780                         break;
1781                     default:
1782                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
1783                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
1784                         break;
1785                 }
1786                 break;
1787             case AST_OPTION_TDD:  /* turn on or off TDD */
1788                 if (!*cp) { /* turn it off */
1789                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
1790                         if (p->tdd) tdd_free(p->tdd);
1791                         p->tdd = 0;
1792                         p->mate = 0;
1793                         break;
1794                 }
1795                 if (*cp == 2)
1796                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
1797                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
1798                 p->mate = 0;
1799                 zt_disable_ec(p);
1800                 /* otherwise, turn it on */
1801                 if (!p->didtdd) { /* if havent done it yet */
1802                         unsigned char mybuf[41000],*buf;
1803                         int size,res,fd,len;
1804                         int index;
1805                         fd_set wfds,efds;
1806                         buf = mybuf;
1807                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
1808                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
1809                         len = 40000;
1810                         index = zt_get_index(chan, p, 0);
1811                         if (index < 0) {
1812                                 ast_log(LOG_WARNING, "No index in TDD?\n");
1813                                 return -1;
1814                         }
1815                         fd = p->subs[index].zfd;
1816                         while(len) {
1817                                 if (ast_check_hangup(chan)) return -1;
1818                                 size = len;
1819                                 if (size > READ_SIZE)
1820                                         size = READ_SIZE;
1821                                 FD_ZERO(&wfds);
1822                                 FD_ZERO(&efds);
1823                                 FD_SET(fd,&wfds);
1824                                 FD_SET(fd,&efds);                       
1825                                 res = select(fd + 1,NULL,&wfds,&efds,NULL);
1826                                 if (!res) {
1827                                         ast_log(LOG_DEBUG, "select (for write) ret. 0 on channel %d\n", p->channel);
1828                                         continue;
1829                                 }
1830                                   /* if got exception */
1831                                 if (FD_ISSET(fd,&efds)) return -1;
1832                                 if (!FD_ISSET(fd,&wfds)) {
1833                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
1834                                         continue;
1835                                 }
1836                                 res = write(fd, buf, size);
1837                                 if (res != size) {
1838                                         if (res == -1) return -1;
1839                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
1840                                         break;
1841                                 }
1842                                 len -= size;
1843                                 buf += size;
1844                         }
1845                         p->didtdd = 1; /* set to have done it now */            
1846                 }
1847                 if (*cp == 2) { /* Mate mode */
1848                         if (p->tdd) tdd_free(p->tdd);
1849                         p->tdd = 0;
1850                         p->mate = 1;
1851                         break;
1852                         }               
1853                 if (!p->tdd) { /* if we dont have one yet */
1854                         p->tdd = tdd_new(); /* allocate one */
1855                 }               
1856                 break;
1857             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
1858                 if (!*cp)
1859                 {               
1860                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
1861                         x = 0;
1862                 }
1863                 else
1864                 {               
1865                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
1866                         x = 1;
1867                 }
1868                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
1869                 break;
1870             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
1871                 if (!*cp)
1872                 {               
1873                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
1874                         x = 0;
1875                         zt_disable_ec(p);
1876                 }
1877                 else
1878                 {               
1879                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
1880                         x = 1;
1881                 }
1882                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
1883                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d\n", p->channel);
1884                 break;
1885         }
1886         errno = 0;
1887         return 0;
1888 }
1889
1890 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master)
1891 {
1892         /* Unlink a specific slave or all slaves/masters from a given master */
1893         int x;
1894         int hasslaves;
1895         if (!master)
1896                 return;
1897         hasslaves = 0;
1898         for (x=0;x<MAX_SLAVES;x++) {
1899                 if (master->slaves[x]) {
1900                         if (!slave || (master->slaves[x] == slave)) {
1901                                 /* Take slave out of the conference */
1902                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
1903                                 conf_del(&master->confno, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
1904                                 master->slaves[x]->master = NULL;
1905                                 master->slaves[x] = NULL;
1906                         } else
1907                                 hasslaves = 1;
1908                 }
1909                 if (!hasslaves)
1910                         master->inconference = 0;
1911         }
1912         if (!slave) {
1913                 if (master->master) {
1914                         /* Take master out of the conference */
1915                         conf_del(&master->master->confno, &master->subs[SUB_REAL], SUB_REAL);
1916                         hasslaves = 0;
1917                         for (x=0;x<MAX_SLAVES;x++) {
1918                                 if (master->master->slaves[x] == master)
1919                                         master->master->slaves[x] = NULL;
1920                                 else if (master->master->slaves[x])
1921                                         hasslaves = 1;
1922                         }
1923                         if (!hasslaves)
1924                                 master->master->inconference = 0;
1925                 }
1926                 master->master = NULL;
1927         }
1928         update_conf(master);
1929 }
1930
1931 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
1932         int x;
1933         if (!slave || !master) {
1934                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
1935                 return;
1936         }
1937         for (x=0;x<MAX_SLAVES;x++) {
1938                 if (!master->slaves[x]) {
1939                         master->slaves[x] = slave;
1940                         break;
1941                 }
1942         }
1943         if (x >= MAX_SLAVES) {
1944                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
1945                 master->slaves[MAX_SLAVES - 1] = slave;
1946         }
1947         if (slave->master) 
1948                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
1949         slave->master = master;
1950         
1951         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
1952 }
1953
1954 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1955 {
1956         struct ast_channel *who = NULL, *cs[3];
1957         struct zt_pvt *p0, *p1, *op0, *op1;
1958         struct zt_pvt *master=NULL, *slave=NULL;
1959         struct ast_frame *f;
1960         int to;
1961         int inconf = 0;
1962         int nothingok = 0;
1963         int ofd1, ofd2;
1964         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
1965         int os1 = -1, os2 = -1;
1966         struct ast_channel *oc1, *oc2;
1967
1968         /* if need DTMF, cant native bridge */
1969         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1970                 return -2;
1971         p0 = c0->pvt->pvt;
1972         p1 = c1->pvt->pvt;
1973         /* cant do pseudo-channels here */
1974         if ((!p0->sig) || (!p1->sig)) return -2;
1975
1976         ast_pthread_mutex_lock(&c0->lock);
1977         ast_pthread_mutex_lock(&c1->lock);
1978         op0 = p0 = c0->pvt->pvt;
1979         op1 = p1 = c1->pvt->pvt;
1980         ofd1 = c0->fds[0];
1981         ofd2 = c1->fds[0];
1982         oi1 = zt_get_index(c0, p0, 0);
1983         oi2 = zt_get_index(c1, p1, 0);
1984         oc1 = p0->owner;
1985         oc2 = p1->owner;
1986         if ((oi1 < 0) || (oi2 < 0))
1987                 return -1;
1988
1989
1990
1991         ast_pthread_mutex_lock(&p0->lock);
1992         if (pthread_mutex_trylock(&p1->lock)) {
1993                 /* Don't block, due to potential for deadlock */
1994                 ast_pthread_mutex_unlock(&p0->lock);
1995                 ast_pthread_mutex_unlock(&c0->lock);
1996                 ast_pthread_mutex_unlock(&c1->lock);
1997                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
1998                 return -3;
1999         }
2000         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2001                 if (!p0->owner || !p1->owner) {
2002                         /* Currently unowned -- Do nothing.  */
2003                         nothingok = 1;
2004                 } else {
2005                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2006                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2007                                 master = p0;
2008                                 slave = p1;
2009                                 inconf = 1;
2010                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2011                                 master = p1;
2012                                 slave = p0;
2013                                 inconf = 1;
2014                         } else {
2015                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2016                                 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,
2017                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2018                         }
2019                 }
2020         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2021                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2022                         master = p1;
2023                         slave = p0;
2024                 } else {
2025                         nothingok = 1;
2026                 }
2027         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2028                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2029                         master = p0;
2030                         slave = p1;
2031                 } else {
2032                         nothingok  = 1;
2033                 }
2034         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2035                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2036                    don't put us in anything */
2037                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2038                         master = p1;
2039                         slave = p0;
2040                 } else {
2041                         nothingok = 1;
2042                 }
2043         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2044                 /* Same as previous */
2045                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2046                         master = p0;
2047                         slave = p1;
2048                 } else {
2049                         nothingok = 1;
2050                 }
2051         }
2052         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2053                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2054         if (master && slave) {
2055                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2056                    in an active threeway call with a channel that is ringing, we should
2057                    indicate ringing. */
2058                 if ((oi2 == SUB_THREEWAY) && 
2059                         p1->subs[SUB_THREEWAY].inthreeway && 
2060                         p1->subs[SUB_REAL].owner && 
2061                         p1->subs[SUB_REAL].inthreeway && 
2062                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2063                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2064                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2065                                 os2 = p1->subs[SUB_REAL].owner->_state;
2066                 } else {
2067                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2068                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2069                 }
2070                 if ((oi1 == SUB_THREEWAY) && 
2071                         p0->subs[SUB_THREEWAY].inthreeway && 
2072                         p0->subs[SUB_REAL].owner && 
2073                         p0->subs[SUB_REAL].inthreeway && 
2074                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2075                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2076                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2077                                 os1 = p0->subs[SUB_REAL].owner->_state;
2078                 } else {
2079                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2080                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2081                 }
2082                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2083                         if (!p0->echocanbridged || !p1->echocanbridged) {
2084                                 /* Disable echo cancellation if appropriate */
2085                                 zt_disable_ec(p0);
2086                                 zt_disable_ec(p1);
2087                         }
2088                 }
2089                 zt_link(slave, master);
2090                 master->inconference = inconf;
2091         } else if (!nothingok)
2092                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2093
2094         update_conf(p0);
2095         update_conf(p1);
2096         t1 = p0->subs[SUB_REAL].inthreeway;
2097         t2 = p1->subs[SUB_REAL].inthreeway;
2098
2099         ast_pthread_mutex_unlock(&p0->lock);
2100         ast_pthread_mutex_unlock(&p1->lock);
2101
2102         ast_pthread_mutex_unlock(&c0->lock);
2103         ast_pthread_mutex_unlock(&c1->lock);
2104
2105         /* Native bridge failed */
2106         if ((!master || !slave) && !nothingok) {
2107                 if (op0 == p0)
2108                         zt_enable_ec(p0);
2109                 if (op1 == p1)
2110                         zt_enable_ec(p1);
2111                 return -1;
2112         }
2113         
2114         cs[0] = c0;
2115         cs[1] = c1;
2116         cs[2] = NULL;
2117         for (;;) {
2118                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2119                    and then balking if anything is wrong */
2120                 ast_pthread_mutex_lock(&c0->lock);
2121                 ast_pthread_mutex_lock(&c1->lock);
2122                 p0 = c0->pvt->pvt;
2123                 p1 = c1->pvt->pvt;
2124                 if (op0 == p0)
2125                         i1 = zt_get_index(c0, p0, 1);
2126                 if (op1 == p1)
2127                         i2 = zt_get_index(c1, p1, 1);
2128                 ast_pthread_mutex_unlock(&c0->lock);
2129                 ast_pthread_mutex_unlock(&c1->lock);
2130                 if ((op0 != p0) || (op1 != p1) || 
2131                     (ofd1 != c0->fds[0]) || 
2132                         (ofd2 != c1->fds[0]) ||
2133                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2134                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2135                     (oc1 != p0->owner) || 
2136                         (oc2 != p1->owner) ||
2137                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2138                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2139                         (oi1 != i1) ||
2140                         (oi2 != i2)) {
2141                         if (slave && master)
2142                                 zt_unlink(slave, master);
2143                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2144                                                                         op0->channel, oi1, op1->channel, oi2);
2145                         if (op0 == p0)
2146                                 zt_enable_ec(p0);
2147                         if (op1 == p1)
2148                                 zt_enable_ec(p1);
2149                         return -3;
2150                 }
2151                 to = -1;
2152                 who = ast_waitfor_n(cs, 2, &to);
2153                 if (!who) {
2154                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2155                         continue;
2156                 }
2157                 if (who->pvt->pvt == op0) 
2158                         op0->ignoredtmf = 1;
2159                 else if (who->pvt->pvt == op1)
2160                         op1->ignoredtmf = 1;
2161                 f = ast_read(who);
2162                 if (who->pvt->pvt == op0) 
2163                         op0->ignoredtmf = 0;
2164                 else if (who->pvt->pvt == op1)
2165                         op1->ignoredtmf = 0;
2166                 if (!f) {
2167                         *fo = NULL;
2168                         *rc = who;
2169                         if (slave && master)
2170                                 zt_unlink(slave, master);
2171                         if (op0 == p0)
2172                                 zt_enable_ec(p0);
2173                         if (op1 == p1)
2174                                 zt_enable_ec(p1);
2175                         return 0;
2176                 }
2177                 if (f->frametype == AST_FRAME_DTMF) {
2178                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2179                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2180                                 *fo = f;
2181                                 *rc = who;
2182                                 if (slave && master)
2183                                         zt_unlink(slave, master);
2184                                 return 0;
2185                         } else if ((who == c0) && p0->pulsedial) {
2186                                 ast_write(c1, f);
2187                         } else if ((who == c1) && p1->pulsedial) {
2188                                 ast_write(c0, f);
2189                         }
2190                 }
2191                 ast_frfree(f);
2192
2193                 /* Swap who gets priority */
2194                 cs[2] = cs[0];
2195                 cs[0] = cs[1];
2196                 cs[1] = cs[2];
2197         }
2198 }
2199
2200 static int zt_indicate(struct ast_channel *chan, int condition);
2201
2202 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2203 {
2204         struct zt_pvt *p = newchan->pvt->pvt;
2205         int x;
2206         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2207         if (p->owner == oldchan)
2208                 p->owner = newchan;
2209         for (x=0;x<3;x++)
2210                 if (p->subs[x].owner == oldchan) {
2211                         if (!x)
2212                                 zt_unlink(NULL, p);
2213                         p->subs[x].owner = newchan;
2214                 }
2215         if (newchan->_state == AST_STATE_RINGING) 
2216                 zt_indicate(newchan, AST_CONTROL_RINGING);
2217         update_conf(p);
2218         return 0;
2219 }
2220
2221 static int zt_ring_phone(struct zt_pvt *p)
2222 {
2223         int x;
2224         int res;
2225         /* Make sure our transmit state is on hook */
2226         x = 0;
2227         x = ZT_ONHOOK;
2228         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2229         do {
2230                 x = ZT_RING;
2231                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2232 #if 0
2233                 printf("Res: %d, error: %s\n", res, strerror(errno));
2234 #endif                                          
2235                 if (res) {
2236                         switch(errno) {
2237                         case EBUSY:
2238                         case EINTR:
2239                                 /* Wait just in case */
2240                                 usleep(10000);
2241                                 continue;
2242                         case EINPROGRESS:
2243                                 res = 0;
2244                                 break;
2245                         default:
2246                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2247                                 res = 0;
2248                         }
2249                 }
2250         } while (res);
2251         return res;
2252 }
2253
2254 static void *ss_thread(void *data);
2255
2256 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int);
2257
2258 static int attempt_transfer(struct zt_pvt *p)
2259 {
2260         /* In order to transfer, we need at least one of the channels to
2261            actually be in a call bridge.  We can't conference two applications
2262            together (but then, why would we want to?) */
2263         if (p->subs[SUB_REAL].owner->bridge) {
2264                 /* The three-way person we're about to transfer to could still be in MOH, so
2265                    stop if now if appropriate */
2266                 if (p->subs[SUB_THREEWAY].owner->bridge)
2267                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2268                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2269                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2270                 }
2271                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2272                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2273                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2274                         return -1;
2275                 }
2276                 /* Orphan the channel */
2277                 unalloc_sub(p, SUB_THREEWAY);
2278         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2279                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2280                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2281                 }
2282                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2283                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2284                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2285                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2286                         return -1;
2287                 }
2288                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2289                 unalloc_sub(p, SUB_THREEWAY);
2290                 /* Tell the caller not to hangup */
2291                 return 1;
2292         } else {
2293                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2294                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2295                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2296         }
2297         return 0;
2298 }
2299
2300 #ifdef ZAPATA_R2
2301 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2302 {
2303         struct ast_frame *f;
2304         f = &p->subs[index].f;
2305         if (!p->r2) {
2306                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2307                 return NULL;
2308         }
2309         switch(e->e) {
2310         case MFCR2_EVENT_BLOCKED:
2311                 if (option_verbose > 2)
2312                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2313                 break;
2314         case MFCR2_EVENT_UNBLOCKED:
2315                 if (option_verbose > 2)
2316                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2317                 break;
2318         case MFCR2_EVENT_CONFIG_ERR:
2319                 if (option_verbose > 2)
2320                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2321                 break;
2322         case MFCR2_EVENT_RING:
2323                 if (option_verbose > 2)
2324                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2325                 break;
2326         case MFCR2_EVENT_HANGUP:
2327                 if (option_verbose > 2)
2328                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2329                 break;
2330         case MFCR2_EVENT_RINGING:
2331                 if (option_verbose > 2)
2332                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2333                 break;
2334         case MFCR2_EVENT_ANSWER:
2335                 if (option_verbose > 2)
2336                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2337                 break;
2338         case MFCR2_EVENT_HANGUP_ACK:
2339                 if (option_verbose > 2)
2340                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2341                 break;
2342         case MFCR2_EVENT_IDLE:
2343                 if (option_verbose > 2)
2344                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2345                 break;
2346         default:
2347                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2348                 break;
2349         }
2350         return f;
2351 }
2352
2353 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2354 {
2355         int x;
2356         int res;
2357         mfcr2_event_t *e;
2358         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2359         if (res) {
2360                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2361                 return NULL;
2362         }
2363         if (!p->r2) {
2364                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2365                 return NULL;
2366         }
2367         e = mfcr2_cas_signaling_event(p->r2, x);
2368         return e;
2369 }
2370 #endif
2371
2372 static int check_for_conference(struct zt_pvt *p)
2373 {
2374         ZT_CONFINFO ci;
2375         /* Fine if we already have a master, etc */
2376         if (p->master || (p->confno > -1))
2377                 return 0;
2378         memset(&ci, 0, sizeof(ci));
2379         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2380                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2381                 return 0;
2382         }
2383         /* If we have no master and don't have a confno, then 
2384            if we're in a conference, it's probably a MeetMe room or
2385            some such, so don't let us 3-way out! */
2386         if (ci.confno) {
2387                 if (option_verbose > 2) 
2388                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2389                 return 1;
2390         }
2391         return 0;
2392 }
2393
2394 static int get_alarms(struct zt_pvt *p)
2395 {
2396         int res;
2397         ZT_SPANINFO zi;
2398         memset(&zi, 0, sizeof(zi));
2399         zi.spanno = p->span;
2400         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2401         if (res < 0) {
2402                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2403                 return 0;
2404         }
2405         return zi.alarms;
2406 }
2407                         
2408 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2409 {
2410         int res,x;
2411         int index;
2412         struct zt_pvt *p = ast->pvt->pvt;
2413         pthread_t threadid;
2414         pthread_attr_t attr;
2415         struct ast_channel *chan;
2416         pthread_attr_init(&attr);
2417         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2418         index = zt_get_index(ast, p, 0);
2419         p->subs[index].f.frametype = AST_FRAME_NULL;
2420         p->subs[index].f.datalen = 0;
2421         p->subs[index].f.samples = 0;
2422         p->subs[index].f.mallocd = 0;
2423         p->subs[index].f.offset = 0;
2424         p->subs[index].f.src = "zt_handle_event";
2425         p->subs[index].f.data = NULL;
2426         if (index < 0)
2427                 return &p->subs[index].f;
2428         res = zt_get_event(p->subs[index].zfd);
2429         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
2430         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFDIGIT)) {
2431                 if (res & ZT_EVENT_PULSEDIGIT)
2432                         p->pulsedial = 1;
2433                 else
2434                         p->pulsedial = 0;
2435                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
2436                 p->subs[index].f.frametype = AST_FRAME_DTMF;
2437                 p->subs[index].f.subclass = res & 0xff;
2438                 /* Return the captured digit */
2439                 return &p->subs[index].f;
2440         }
2441         switch(res) {
2442                 case ZT_EVENT_BITSCHANGED:
2443                         if (p->sig == SIG_R2) {
2444 #ifdef ZAPATA_R2
2445                                 struct ast_frame  *f = &p->subs[index].f;
2446                                 mfcr2_event_t *e;
2447                                 e = r2_get_event_bits(p);
2448                                 if (e)
2449                                         f = handle_r2_event(p, e, index);
2450                                 return f;
2451 #else                           
2452                                 break;
2453 #endif
2454                         }
2455                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
2456                 case ZT_EVENT_PULSE_START:
2457                         /* Stop tone if there's a pulse start and the PBX isn't started */
2458                         if (!ast->pbx)
2459                                 tone_zone_play_tone(p->subs[index].zfd, -1);
2460                         break;  
2461                 case ZT_EVENT_DIALCOMPLETE:
2462                         if (p->inalarm) break;
2463                         if (p->radio) break;
2464                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
2465                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
2466                                 return NULL;
2467                         }
2468                         if (!x) { /* if not still dialing in driver */
2469                                 zt_enable_ec(p);
2470                                 p->dialing = 0;
2471                                 if (ast->_state == AST_STATE_DIALING) {
2472                                         if (p->callprogress && CANPROGRESSDETECT(p) && p->dsp) {
2473                                                 ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
2474                                         } 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)))) {
2475                                                 ast_setstate(ast, AST_STATE_RINGING);
2476                                         } else {
2477                                                 ast_setstate(ast, AST_STATE_UP);
2478                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2479                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2480                                         }
2481                                 }
2482                         }
2483                         break;
2484                 case ZT_EVENT_ALARM:
2485                         p->inalarm = 1;
2486                         res = get_alarms(p);
2487                         ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
2488                         /* fall through intentionally */
2489                 case ZT_EVENT_ONHOOK:
2490                         if (p->radio)
2491                         {
2492                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2493                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
2494                                 break;
2495                         }
2496                         switch(p->sig) {
2497                         case SIG_FXOLS:
2498                         case SIG_FXOGS:
2499                         case SIG_FXOKS:
2500                                 p->onhooktime = time(NULL);
2501                                 p->msgstate = -1;
2502                                 /* Check for some special conditions regarding call waiting */
2503                                 if (index == SUB_REAL) {
2504                                         /* The normal line was hung up */
2505                                         if (p->subs[SUB_CALLWAIT].owner) {
2506                                                 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2507                                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2508                                                 if (option_verbose > 2) 
2509                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2510                                                 unalloc_sub(p, SUB_CALLWAIT);   
2511 #if 0
2512                                                 p->subs[index].needanswer = 0;
2513                                                 p->subs[index].needringing = 0;
2514 #endif                                          
2515                                                 p->callwaitingrepeat = 0;
2516                                                 p->cidcwexpire = 0;
2517                                                 p->owner = NULL;
2518                                                 zt_ring_phone(p);
2519                                         } else if (p->subs[SUB_THREEWAY].owner) {
2520                                                 struct timeval tv;
2521                                                 unsigned int mssinceflash;
2522                                                 gettimeofday(&tv, NULL);
2523                                                 mssinceflash = (tv.tv_sec - p->flashtime.tv_sec) * 1000 + (tv.tv_usec - p->flashtime.tv_usec) / 1000;
2524                                                 if (mssinceflash < MIN_MS_SINCE_FLASH) {
2525                                                         /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
2526                                                            hanging up.  Hangup both channels now */
2527                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2528                                                         ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2529                                                 } else if ((ast->pbx) ||
2530                                                         (ast->_state == AST_STATE_UP)) {
2531                                                         if (p->transfer) {
2532                                                                 /* In any case this isn't a threeway call anymore */
2533                                                                 p->subs[SUB_REAL].inthreeway = 0;
2534                                                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2535                                                                 if ((res = attempt_transfer(p)) < 0)
2536                                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2537                                                                 else if (res) {
2538                                                                         /* Don't actually hang up at this point */
2539                                                                         break;
2540                                                                 }
2541                                                         } else
2542                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2543                                                 } else {
2544                                                         /* Swap subs and dis-own channel */
2545                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2546                                                         p->owner = NULL;
2547                                                         /* Ring the phone */
2548                                                         zt_ring_phone(p);
2549                                                 }
2550                                         }
2551                                 } else {
2552                                         ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
2553                                 }
2554                                 /* Fall through */
2555                         default:
2556                                 zt_disable_ec(p);
2557                                 return NULL;
2558                         }
2559                         break;
2560                 case ZT_EVENT_RINGOFFHOOK:
2561                         if (p->inalarm) break;
2562                         if (p->radio)
2563                         {
2564                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2565                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
2566                                 break;
2567                         }
2568                         switch(p->sig) {
2569                         case SIG_FXOLS:
2570                         case SIG_FXOGS:
2571                         case SIG_FXOKS:
2572                                 switch(ast->_state) {
2573                                 case AST_STATE_RINGING:
2574                                         zt_enable_ec(p);
2575                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2576                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2577                                         /* Make sure it stops ringing */
2578                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
2579                                         ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
2580                                         if (p->cidspill) {
2581                                                 /* Cancel any running CallerID spill */
2582                                                 free(p->cidspill);
2583                                                 p->cidspill = NULL;
2584                                         }
2585                                         p->dialing = 0;
2586                                         p->callwaitcas = 0;
2587                                         if (p->confirmanswer) {
2588                                                 /* Ignore answer if "confirm answer" is selected */
2589                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2590                                                 p->subs[index].f.subclass = 0;
2591                                         } else 
2592                                                 ast_setstate(ast, AST_STATE_UP);
2593                                         return &p->subs[index].f;
2594                                 case AST_STATE_DOWN:
2595                                         ast_setstate(ast, AST_STATE_RING);
2596                                         ast->rings = 1;
2597                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2598                                         p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
2599                                         ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
2600                                         return &p->subs[index].f;
2601                                 case AST_STATE_UP:
2602                                         /* Make sure it stops ringing */
2603                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
2604                                         /* Okay -- probably call waiting*/
2605                                         if (p->owner->bridge)
2606                                                         ast_moh_stop(p->owner->bridge);
2607                                         break;
2608                                 default:
2609                                         ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
2610                                 }
2611                                 break;
2612                         case SIG_FXSLS:
2613                         case SIG_FXSGS:
2614                         case SIG_FXSKS:
2615                                 if (ast->_state == AST_STATE_RING) {
2616                                         p->ringt = RINGT;
2617                                 }
2618                                 /* Fall through */
2619                         case SIG_EM:
2620                         case SIG_EMWINK:
2621                         case SIG_FEATD:
2622                         case SIG_FEATDMF:
2623                         case SIG_FEATB:
2624                         case SIG_SF:
2625                         case SIG_SFWINK:
2626                         case SIG_SF_FEATD:
2627                         case SIG_SF_FEATDMF:
2628                         case SIG_SF_FEATB:
2629                                 if (ast->_state == AST_STATE_DOWN) {
2630                                         if (option_debug)
2631                                                 ast_log(LOG_DEBUG, "Ring detected\n");
2632                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2633                                         p->subs[index].f.subclass = AST_CONTROL_RING;
2634                                 } else if (ast->_state == AST_STATE_RINGING) {
2635                                         if (option_debug)
2636                                                 ast_log(LOG_DEBUG, "Line answered\n");
2637                                         if (p->confirmanswer) {
2638                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2639                                                 p->subs[index].f.subclass = 0;
2640                                         } else {
2641                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2642                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2643                                                 ast_setstate(ast, AST_STATE_UP);
2644                                         }
2645                                 } else if (ast->_state != AST_STATE_RING)
2646                                         ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
2647                                 break;
2648                         default:
2649                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
2650                         }
2651                         break;
2652                 case ZT_EVENT_RINGEROFF:
2653                         if (p->inalarm) break;
2654                         if (p->radio) break;
2655                         ast->rings++;
2656                         if ((ast->rings > p->cidrings) && (p->cidspill)) {
2657                                 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
2658                                 free(p->cidspill);
2659                                 p->cidspill = NULL;
2660                                 p->callwaitcas = 0;
2661                         }
2662                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2663                         p->subs[index].f.subclass = AST_CONTROL_RINGING;
2664                         break;
2665                 case ZT_EVENT_RINGERON:
2666                         break;
2667                 case ZT_EVENT_NOALARM:
2668                         p->inalarm = 0;
2669                         ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
2670                         break;
2671                 case ZT_EVENT_WINKFLASH:
2672                         if (p->inalarm) break;
2673                         if (p->radio) break;
2674                         /* Remember last time we got a flash-hook */
2675                         gettimeofday(&p->flashtime, NULL);
2676                         switch(p->sig) {
2677                         case SIG_FXOLS:
2678                         case SIG_FXOGS:
2679                         case SIG_FXOKS:
2680                                 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
2681                                         index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2682                                 p->callwaitcas = 0;
2683                                 if (index == SUB_REAL) {
2684                                         if (p->subs[SUB_CALLWAIT].owner) {
2685                                                 /* Swap to call-wait */
2686                                                 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
2687                                                 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2688                                                 p->owner = p->subs[SUB_REAL].owner;
2689                                                 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
2690                                                 if (p->owner->_state == AST_STATE_RINGING) {
2691                                                         ast_setstate(p->owner, AST_STATE_UP);
2692                                                         p->subs[SUB_REAL].needanswer = 1;
2693                                                 }
2694                                                 p->callwaitingrepeat = 0;
2695                                                 p->cidcwexpire = 0;
2696                                                 /* Start music on hold if appropriate */
2697                                                 if (!p->subs[SUB_CALLWAIT].inthreeway && p->subs[SUB_CALLWAIT].owner->bridge)
2698                                                                 ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
2699                                                 if (p->subs[SUB_REAL].owner->bridge)
2700                                                                 ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
2701                                         } else if (!p->subs[SUB_THREEWAY].owner) {
2702                                                 if (p->threewaycalling && !check_for_conference(p)) {
2703                                                         /* XXX This section needs much more error checking!!! XXX */
2704                                                         /* Start a 3-way call if feasible */
2705                                                         if ((ast->pbx) ||
2706                                                                         (ast->_state == AST_STATE_UP) ||
2707                                                                         (ast->_state == AST_STATE_RING)) {
2708                                                                 if (!alloc_sub(p, SUB_THREEWAY)) {
2709                                                                         /* Make new channel */
2710                                                                         chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0);
2711                                                                         /* Swap things around between the three-way and real call */
2712                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2713                                                                         /* Disable echo canceller for better dialing */
2714                                                                         zt_disable_ec(p);
2715                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
2716                                                                         if (res)
2717                                                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
2718                                                                         p->owner = chan;
2719                                                                         if (pthread_create(&threadid, &attr, ss_thread, chan)) {
2720                                                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
2721                                                                                 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2722                                                                                 zt_enable_ec(p);
2723                                                                                 ast_hangup(chan);
2724                                                                         } else {
2725                                                                                 if (option_verbose > 2) 
2726                                                                                         ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
2727                                                                                 /* Start music on hold if appropriate */
2728                                                                                 if (p->subs[SUB_THREEWAY].owner->bridge)
2729                                                                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
2730                                                                         }               
2731                                                                 } else
2732                                                                         ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
2733                                                         } else 
2734                                                                 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
2735                                                 }
2736                                         } else {
2737                                                 /* Already have a 3 way call */
2738                                                 if (p->subs[SUB_THREEWAY].inthreeway) {
2739                                                         /* Call is already up, drop the last person */
2740                                                         if (option_debug)
2741                                                                 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
2742                                                         /* If the primary call isn't answered yet, use it */
2743                                                         if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
2744                                                                 /* Swap back -- we're droppign the real 3-way that isn't finished yet*/
2745                                                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2746                                                                 p->owner = p->subs[SUB_REAL].owner;
2747                                                         }
2748                                                         /* Drop the last call and stop the conference */
2749                                                         if (option_verbose > 2)
2750                                                                 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
2751                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2752                                                         p->subs[SUB_REAL].inthreeway = 0;
2753                                                         p->subs[SUB_THREEWAY].inthreeway = 0;
2754                                                 } else {
2755                                                         /* Lets see what we're up to */
2756                                                         if ((ast->pbx) ||
2757                                                                         (ast->_state == AST_STATE_UP)) {
2758                                                                 int otherindex = SUB_THREEWAY;
2759                                                                 if (option_verbose > 2)
2760                                                                         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);
2761                                                                 /* Put them in the threeway, and flip */
2762                                                                 p->subs[SUB_THREEWAY].inthreeway = 1;
2763                                                                 p->subs[SUB_REAL].inthreeway = 1;
2764                                                                 if (ast->_state == AST_STATE_UP) {
2765                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2766                                                                         otherindex = SUB_REAL;
2767                                                                 }
2768                                                                 if (p->subs[otherindex].owner && p->subs[otherindex].owner->bridge)
2769                                                                         ast_moh_stop(p->subs[otherindex].owner->bridge);
2770                                                                 p->owner = p->subs[SUB_REAL].owner;
2771                                                                 if (ast->_state == AST_STATE_RINGING) {
2772                                                                         ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
2773                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
2774                                                                         res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
2775                                                                 }
2776                                                         } else {
2777                                                                 if (option_verbose > 2)
2778                                                                         ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
2779                                                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2780                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2781                                                                 p->owner = p->subs[SUB_REAL].owner;
2782                                                                 if (p->subs[SUB_REAL].owner && p->subs[SUB_REAL].owner->bridge)
2783                                                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
2784                                                                 zt_enable_ec(p);
2785                                                         }
2786                                                         
2787                                                 }
2788                                         }
2789                                 } else {
2790                                         ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
2791                                 }
2792                                 update_conf(p);
2793                                 break;
2794                         case SIG_EM:
2795                         case SIG_EMWINK:
2796                         case SIG_FEATD:
2797                         case SIG_SF:
2798                         case SIG_SFWINK:
2799                         case SIG_SF_FEATD:
2800                         case SIG_FXSLS:
2801                         case SIG_FXSGS:
2802                                 if (p->dialing)
2803                                         ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
2804                                 else
2805                                         ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
2806                                 break;
2807                         case SIG_FEATDMF:
2808                         case SIG_FEATB:
2809                         case SIG_SF_FEATDMF:
2810                         case SIG_SF_FEATB:
2811                                 /* FGD MF *Must* wait for wink */
2812                                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2813                                 if (res < 0) {
2814                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
2815                                         p->dop.dialstr[0] = '\0';