If a hangup occurs within 1000ms of a flash, consider it a bounce, and just hangup...
[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
675         index = zt_get_index(ast, p, 0);
676         if (index == SUB_REAL) {
677                 zo.op = ZT_DIAL_OP_APPEND;
678                 zo.dialstr[0] = 'T';
679                 zo.dialstr[1] = digit;
680                 zo.dialstr[2] = 0;
681                 if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
682                         ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
683                 else
684                         p->dialing = 1;
685         }
686         
687         return res;
688 }
689
690 static char *events[] = {
691         "No event",
692         "On hook",
693         "Ring/Answered",
694         "Wink/Flash",
695         "Alarm",
696         "No more alarm",
697                 "HDLC Abort",
698                 "HDLC Overrun",
699                 "HDLC Bad FCS",
700                 "Dial Complete",
701                 "Ringer On",
702                 "Ringer Off",
703                 "Hook Transition Complete",
704                 "Bits Changed",
705                 "Pulse Start"
706 };
707
708 static struct {
709         int alarm;
710         char *name;
711 } alarms[] = {
712         { ZT_ALARM_RED, "Red Alarm" },
713         { ZT_ALARM_YELLOW, "Yellow Alarm" },
714         { ZT_ALARM_BLUE, "Blue Alarm" },
715         { ZT_ALARM_RECOVER, "Recovering" },
716         { ZT_ALARM_LOOPBACK, "Loopback" },
717         { ZT_ALARM_NOTOPEN, "Not Open" },
718         { ZT_ALARM_NONE, "None" },
719 };
720
721 static char *alarm2str(int alarm)
722 {
723         int x;
724         for (x=0;x<sizeof(alarms) / sizeof(alarms[0]); x++) {
725                 if (alarms[x].alarm & alarm)
726                         return alarms[x].name;
727         }
728         return alarm ? "Unknown Alarm" : "No Alarm";
729 }
730
731 static char *event2str(int event)
732 {
733         static char buf[256];
734         if ((event < 15) && (event > -1))
735                 return events[event];
736         sprintf(buf, "Event %d", event);
737         return buf;
738 }
739
740 #ifdef ZAPATA_R2
741 static int str2r2prot(char *swtype)
742 {
743     if (!strcasecmp(swtype, "ar"))
744         return MFCR2_PROT_ARGENTINA;
745     /*endif*/
746     if (!strcasecmp(swtype, "cn"))
747         return MFCR2_PROT_CHINA;
748     /*endif*/
749     if (!strcasecmp(swtype, "kr"))
750         return MFCR2_PROT_KOREA;
751     /*endif*/
752     return -1;
753 }
754 #endif
755
756 static char *sig2str(int sig)
757 {
758         static char buf[256];
759         switch(sig) {
760         case SIG_EM:
761                 return "E & M Immediate";
762         case SIG_EMWINK:
763                 return "E & M Wink";
764         case SIG_FEATD:
765                 return "Feature Group D (DTMF)";
766         case SIG_FEATDMF:
767                 return "Feature Group D (MF)";
768         case SIG_FEATB:
769                 return "Feature Group B (MF)";
770         case SIG_FXSLS:
771                 return "FXS Loopstart";
772         case SIG_FXSGS:
773                 return "FXS Groundstart";
774         case SIG_FXSKS:
775                 return "FXS Kewlstart";
776         case SIG_FXOLS:
777                 return "FXO Loopstart";
778         case SIG_FXOGS:
779                 return "FXO Groundstart";
780         case SIG_FXOKS:
781                 return "FXO Kewlstart";
782         case SIG_PRI:
783                 return "PRI Signalling";
784         case SIG_R2:
785                 return "R2 Signalling";
786         case SIG_SF:
787                 return "SF (Tone) Signalling Immediate";
788         case SIG_SFWINK:
789                 return "SF (Tone) Signalling Wink";
790         case SIG_SF_FEATD:
791                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
792         case SIG_SF_FEATDMF:
793                 return "SF (Tone) Signallong with Feature Group D (MF)";
794         case SIG_SF_FEATB:
795                 return "SF (Tone) Signalling with Feature Group B (MF)";
796         case 0:
797                 return "Pseudo Signalling";
798         default:
799                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
800                 return buf;
801         }
802 }
803
804 static int conf_add(int *confno, struct zt_subchannel *c, int index)
805 {
806         /* If the conference already exists, and we're already in it
807            don't bother doing anything */
808         ZT_CONFINFO zi;
809         if ((*confno > 0) && (c->curconfno == *confno))
810                 return 0; 
811         if (c->curconfno > 0) {
812                 ast_log(LOG_WARNING, "Subchannel %d is already in conference %d, moving to %d\n", c->zfd, c->curconfno, *confno);
813         }
814         if (c->zfd < 0)
815                 return 0;
816         memset(&zi, 0, sizeof(zi));
817         zi.chan = 0;
818         zi.confno = *confno;
819         if (!index) {
820                 /* Real-side and pseudo-side both participate in conference */
821                 zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
822                                                         ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
823         } else
824                 zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
825         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
826                 ast_log(LOG_WARNING, "Failed to add %d to conference %d\n", c->zfd, *confno);
827                 return -1;
828         }
829         c->curconfno = zi.confno;
830         *confno = zi.confno;
831         ast_log(LOG_DEBUG, "Added %d to conference %d\n", c->zfd, *confno);
832         return 0;
833 }
834
835 static int conf_del(int *confno, struct zt_subchannel *c, int index)
836 {
837         ZT_CONFINFO zi;
838                 /* Can't delete from this conference if it's not 0 */
839         if ((*confno < 1) ||
840                 /* Can't delete if there's no zfd */
841                 (c->zfd < 0) ||
842                 /* Don't delete from the conference if it's not our conference */
843                 (*confno != c->curconfno) 
844                 /* Don't delete if we don't think it's conferenced at all (implied) */
845                 ) return 0;
846         memset(&zi, 0, sizeof(zi));
847         zi.chan = 0;
848         zi.confno = 0;
849         zi.confmode = 0;
850         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
851                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d\n", c->zfd, *confno);
852                 return -1;
853         }
854         c->curconfno = -1;
855         ast_log(LOG_DEBUG, "Removed %d from conference %d\n", c->zfd, *confno);
856         return 0;
857 }
858
859 static int update_conf(struct zt_pvt *p)
860 {
861         int needconf = 0;
862         int x;
863         /* Update conference state in a stateless fashion */
864         /* Start with the obvious, general stuff */
865         for (x=0;x<3;x++) {
866                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
867                         conf_add(&p->confno, &p->subs[x], x);
868                         needconf++;
869                 } else {
870                         conf_del(&p->confno, &p->subs[x], x);
871                 }
872         }
873         /* If we have a slave, add him to our conference now */
874         for (x=0;x<MAX_SLAVES;x++) {
875                 if (p->slaves[x]) {
876                         conf_add(&p->confno, &p->slaves[x]->subs[SUB_REAL], SUB_REAL);
877                         needconf++;
878                 }
879         }
880         /* If we're supposed to be in there, do so now */
881         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
882                 conf_add(&p->confno, &p->subs[SUB_REAL], SUB_REAL);
883                 needconf++;
884         }
885         /* If we have a master, add ourselves to his conference */
886         if (p->master) 
887                 conf_add(&p->master->confno, &p->subs[SUB_REAL], SUB_REAL);
888         if (!needconf) {
889                 /* Nobody is left (or should be left) in our conference.  
890                    Kill it.  */
891                 p->confno = -1;
892         }
893         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
894         return 0;
895 }
896
897 static void zt_enable_ec(struct zt_pvt *p)
898 {
899         int x;
900         int res;
901         if (p->echocanon) {
902                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
903                 return;
904         }
905         if (p && p->echocancel) {
906                 x = p->echocancel;
907                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
908                 if (res) 
909                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
910                 else {
911                         p->echocanon = 1;
912                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
913                 }
914         } else
915                 ast_log(LOG_DEBUG, "No echocancellation requested\n");
916 }
917
918 static void zt_disable_ec(struct zt_pvt *p)
919 {
920         int x;
921         int res;
922         if (p->echocancel) {
923                 x = 0;
924                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
925                 if (res) 
926                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
927                 else
928                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
929         }
930         p->echocanon = 0;
931 }
932
933 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
934 {
935         struct  zt_gains g;
936         float ltxgain;
937         float lrxgain;
938         int j,k;
939         g.chan = chan;
940         if ((rxgain != 0.0)  || (txgain != 0.0)) {
941                 /* caluculate linear value of tx gain */
942                 ltxgain = pow(10.0,txgain / 20.0);
943                 /* caluculate linear value of rx gain */
944                 lrxgain = pow(10.0,rxgain / 20.0);
945                 if (law == ZT_LAW_ALAW) {
946                         for (j=0;j<256;j++) {
947                                 k = (int)(((float)AST_ALAW(j)) * lrxgain);
948                                 if (k > 32767) k = 32767;
949                                 if (k < -32767) k = -32767;
950                                 g.rxgain[j] = AST_LIN2A(k);
951                                 k = (int)(((float)AST_ALAW(j)) * ltxgain);
952                                 if (k > 32767) k = 32767;
953                                 if (k < -32767) k = -32767;
954                                 g.txgain[j] = AST_LIN2A(k);
955                         }
956                 } else {
957                         for (j=0;j<256;j++) {
958                                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
959                                 if (k > 32767) k = 32767;
960                                 if (k < -32767) k = -32767;
961                                 g.rxgain[j] = AST_LIN2MU(k);
962                                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
963                                 if (k > 32767) k = 32767;
964                                 if (k < -32767) k = -32767;
965                                 g.txgain[j] = AST_LIN2MU(k);
966                         }
967                 }
968         } else {
969                 for (j=0;j<256;j++) {
970                         g.rxgain[j] = j;
971                         g.txgain[j] = j;
972                 }
973         }
974                 
975           /* set 'em */
976         return(ioctl(fd,ZT_SETGAINS,&g));
977 }
978
979 static inline int zt_set_hook(int fd, int hs)
980 {
981         int x, res;
982         x = hs;
983         res = ioctl(fd, ZT_HOOK, &x);
984         if (res < 0) 
985         {
986                 if (errno == EINPROGRESS) return 0;
987                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
988         }
989         return res;
990 }
991
992 static inline int zt_confmute(struct zt_pvt *p, int muted)
993 {
994         int x, res;
995         x = muted;
996         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
997         if (res < 0) 
998                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
999         return res;
1000 }
1001
1002 static int save_conference(struct zt_pvt *p)
1003 {
1004         struct zt_confinfo c;
1005         int res;
1006         if (p->saveconf.confmode) {
1007                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1008                 return -1;
1009         }
1010         p->saveconf.chan = 0;
1011         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1012         if (res) {
1013                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1014                 p->saveconf.confmode = 0;
1015                 return -1;
1016         }
1017         c.chan = 0;
1018         c.confno = 0;
1019         c.confmode = ZT_CONF_NORMAL;
1020         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1021         if (res) {
1022                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1023                 return -1;
1024         }
1025         if (option_debug)
1026                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1027         return 0;
1028 }
1029
1030 static int restore_conference(struct zt_pvt *p)
1031 {
1032         int res;
1033         if (p->saveconf.confmode) {
1034                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1035                 p->saveconf.confmode = 0;
1036                 if (res) {
1037                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1038                         return -1;
1039                 }
1040         }
1041         if (option_debug)
1042                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1043         return 0;
1044 }
1045
1046 static int send_callerid(struct zt_pvt *p);
1047
1048 int send_cwcidspill(struct zt_pvt *p)
1049 {
1050         p->callwaitcas = 0;
1051         p->cidcwexpire = 0;
1052         p->cidspill = malloc(MAX_CALLERID_SIZE);
1053         if (p->cidspill) {
1054                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
1055                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwaitcid, AST_LAW(p));
1056                 /* Make sure we account for the end */
1057                 p->cidlen += READ_SIZE * 4;
1058                 p->cidpos = 0;
1059                 send_callerid(p);
1060                 if (option_verbose > 2)
1061                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s'\n", p->callwaitcid);
1062         } else return -1;
1063         return 0;
1064 }
1065
1066 static int has_voicemail(struct zt_pvt *p)
1067 {
1068
1069         return ast_app_has_voicemail(p->mailbox);
1070 }
1071
1072 static int send_callerid(struct zt_pvt *p)
1073 {
1074         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1075         int res;
1076         /* Take out of linear mode if necessary */
1077         if (p->subs[SUB_REAL].linear) {
1078                 p->subs[SUB_REAL].linear = 0;
1079                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1080         }
1081         while(p->cidpos < p->cidlen) {
1082                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1083                 if (res < 0) {
1084                         if (errno == EAGAIN)
1085                                 return 0;
1086                         else {
1087                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1088                                 return -1;
1089                         }
1090                 }
1091                 if (!res)
1092                         return 0;
1093                 p->cidpos += res;
1094         }
1095         free(p->cidspill);
1096         p->cidspill = NULL;
1097         if (p->callwaitcas) {
1098                 /* Wait for CID/CW to expire */
1099                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1100         } else
1101                 restore_conference(p);
1102         return 0;
1103 }
1104
1105 static int zt_callwait(struct ast_channel *ast)
1106 {
1107         struct zt_pvt *p = ast->pvt->pvt;
1108         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1109         if (p->cidspill) {
1110                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1111                 free(p->cidspill);
1112         }
1113         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
1114         if (p->cidspill) {
1115                 save_conference(p);
1116                 /* Silence */
1117                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1118                 if (!p->callwaitrings && p->callwaitingcallerid) {
1119                         ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1120                         p->callwaitcas = 1;
1121                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
1122                 } else {
1123                         ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1124                         p->callwaitcas = 0;
1125                         p->cidlen = 2400 + READ_SIZE * 4;
1126                 }
1127                 p->cidpos = 0;
1128                 send_callerid(p);
1129         } else {
1130                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
1131                 return -1;
1132         }
1133         return 0;
1134 }
1135
1136 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1137 {
1138         struct zt_pvt *p = ast->pvt->pvt;
1139         int x, res, index;
1140         char *c, *n, *l;
1141         char *s;
1142         char callerid[256];
1143         char dest[256];
1144         strncpy(dest, rdest, sizeof(dest) - 1);
1145         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1146                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1147                 return -1;
1148         }
1149         p->dialednone = 0;
1150         if (p->radio)  /* if a radio channel, up immediately */
1151         {
1152                 /* Special pseudo -- automatically up */
1153                 ast_setstate(ast, AST_STATE_UP); 
1154                 return 0;
1155         }
1156         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1157         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1158         if (res)
1159                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1160         p->outgoing = 1;
1161
1162         switch(p->sig) {
1163         case SIG_FXOLS:
1164         case SIG_FXOGS:
1165         case SIG_FXOKS:
1166                 if (p->owner == ast) {
1167                         /* Normal ring, on hook */
1168                         
1169                         /* Don't send audio while on hook, until the call is answered */
1170                         p->dialing = 1;
1171                         if (p->use_callerid) {
1172                                 /* Generate the Caller-ID spill if desired */
1173                                 if (p->cidspill) {
1174                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1175                                         free(p->cidspill);
1176                                 }
1177                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
1178                                 p->callwaitcas = 0;
1179                                 if (p->cidspill) {
1180                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->callerid, AST_LAW(p));
1181                                         p->cidpos = 0;
1182                                         send_callerid(p);
1183                                 } else
1184                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
1185                         }
1186                         /* Select proper cadence */
1187                         if ((p->distinctivering > 0) && (p->distinctivering <= NUM_CADENCE)) {
1188                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1189                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1190                                 p->cidrings = cidrings[p->distinctivering - 1];
1191                         } else {
1192                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1193                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1194                                 p->cidrings = 1;
1195                         }
1196                         x = ZT_RING;
1197                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1198                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1199                                 return -1;
1200                         }
1201                         p->dialing = 1;
1202                 } else {
1203                         /* Call waiting call */
1204                         p->callwaitrings = 0;
1205                         if (ast->callerid)
1206                                 strncpy(p->callwaitcid, ast->callerid, sizeof(p->callwaitcid)-1);
1207                         else
1208                                 strcpy(p->callwaitcid, "");
1209                         /* Call waiting tone instead */
1210                         if (zt_callwait(ast))
1211                                 return -1;
1212                         /* Make ring-back */
1213                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1214                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1215                                 
1216                 }
1217                 if (ast->callerid) 
1218                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1219                 else
1220                         strcpy(callerid, "");
1221                 ast_callerid_parse(callerid, &n, &l);
1222                 if (l) {
1223                         ast_shrink_phone_number(l);
1224                         if (!ast_isphonenumber(l))
1225                                 l = NULL;
1226                 }
1227                 if (l)
1228                         strcpy(p->lastcallerid, l);
1229                 else
1230                         strcpy(p->lastcallerid, "");
1231                 ast_setstate(ast, AST_STATE_RINGING);
1232                 index = zt_get_index(ast, p, 0);
1233                 if (index > -1) {
1234                         p->subs[index].needringing = 1;
1235                 }
1236                 break;
1237         case SIG_FXSLS:
1238         case SIG_FXSGS:
1239         case SIG_FXSKS:
1240         case SIG_EMWINK:
1241         case SIG_EM:
1242         case SIG_FEATD:
1243         case SIG_FEATDMF:
1244         case SIG_FEATB:
1245         case SIG_SFWINK:
1246         case SIG_SF:
1247         case SIG_SF_FEATD:
1248         case SIG_SF_FEATDMF:
1249         case SIG_SF_FEATB:
1250                 c = strchr(dest, '/');
1251                 if (c)
1252                         c++;
1253                 else
1254                         c = dest;
1255                 if (strlen(c) < p->stripmsd) {
1256                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1257                         return -1;
1258                 }
1259                 x = ZT_START;
1260                 /* Start the trunk */
1261                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1262                 if (res < 0) {
1263                         if (errno != EINPROGRESS) {
1264                                 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1265                                 return -1;
1266                         }
1267                 }
1268                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1269                 p->dop.op = ZT_DIAL_OP_REPLACE;
1270                 if (p->sig == SIG_FEATD) {
1271                         if (ast->callerid) {
1272                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1273                                 ast_callerid_parse(callerid, &n, &l);
1274                                 if (l) {
1275                                         ast_shrink_phone_number(l);
1276                                         if (!ast_isphonenumber(l))
1277                                                 l = NULL;
1278                                 }
1279                         } else
1280                                 l = NULL;
1281                         if (l) 
1282                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1283                         else
1284                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1285                 } else 
1286                 if (p->sig == SIG_FEATDMF) {
1287                         if (ast->callerid) {
1288                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1289                                 ast_callerid_parse(callerid, &n, &l);
1290                                 if (l) {
1291                                         ast_shrink_phone_number(l);
1292                                         if (!ast_isphonenumber(l))
1293                                                 l = NULL;
1294                                 }
1295                         } else
1296                                 l = NULL;
1297                         if (l) 
1298                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1299                         else
1300                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1301                 } else 
1302                 if (p->sig == SIG_FEATB) {
1303                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1304                 } else 
1305                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", c + p->stripmsd);
1306                 if (!res) {
1307                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1308                                 x = ZT_ONHOOK;
1309                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1310                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1311                                 return -1;
1312                         }
1313                 } else
1314                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1315                 p->dialing = 1;
1316                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1317                 ast_setstate(ast, AST_STATE_DIALING);
1318                 break;
1319 #ifdef ZAPATA_PRI
1320         case SIG_PRI:
1321                 c = strchr(dest, '/');
1322                 if (c)
1323                         c++;
1324                 else
1325                         c = dest;
1326                 if (ast->callerid) {
1327                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1328                         ast_callerid_parse(callerid, &n, &l);
1329                         if (l) {
1330                                 ast_shrink_phone_number(l);
1331                                 if (!ast_isphonenumber(l))
1332                                         l = NULL;
1333                         }
1334                 } else
1335                         l = NULL;
1336                 if (strlen(c) < p->stripmsd) {
1337                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1338                         return -1;
1339                 }
1340                 p->dop.op = ZT_DIAL_OP_REPLACE;
1341                 s = strchr(c + p->stripmsd, 'w');
1342                 if (s) {
1343                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1344                         *s = '\0';
1345                 } else {
1346                         strcpy(p->dop.dialstr, "");
1347                 }
1348                 if (!(p->call = pri_new_call(p->pri->pri))) {
1349                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1350                         return -1;
1351                 }
1352                 if (pri_call(p->pri->pri, p->call, p->digital ? PRI_TRANS_CAP_DIGITAL : PRI_TRANS_CAP_SPEECH, 
1353                         p->prioffset, p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1, l, p->pri->dialplan - 1, n,
1354                         l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE,
1355                         c + p->stripmsd, p->pri->dialplan - 1, 
1356                         ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW))) {
1357                         ast_log(LOG_WARNING, "Unable to setup call to %s\n", c + p->stripmsd);
1358                         return -1;
1359                 }
1360                 ast_setstate(ast, AST_STATE_DIALING);
1361                 break;
1362 #endif          
1363         case 0:
1364                 /* Special pseudo -- automatically up*/
1365                 ast_setstate(ast, AST_STATE_UP);
1366                 break;          
1367         default:
1368                 ast_log(LOG_DEBUG, "not yet implemented\n");
1369                 return -1;
1370         }
1371         return 0;
1372 }
1373
1374 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1375 {
1376         int owned = 0;
1377         int i = 0;
1378
1379         if (!now) {
1380                 if (cur->owner) {
1381                         owned = 1;
1382                 }
1383
1384                 for (i = 0; i < 3; i++) {
1385                         if (cur->subs[i].owner) {
1386                                 owned = 1;
1387                         }
1388                 }
1389                 if (!owned) {
1390                         if (prev) {
1391                                 prev->next = cur->next;
1392                         } else {
1393                                 iflist = cur->next;
1394                         }
1395                         if (cur->subs[SUB_REAL].zfd > -1) {
1396                                 zt_close(cur->subs[SUB_REAL].zfd);
1397                         }
1398                         free(cur);
1399                 }
1400         } else {
1401                 if (prev) {
1402                         prev->next = cur->next;
1403                 } else {
1404                         iflist = cur->next;
1405                 }
1406                 if (cur->subs[SUB_REAL].zfd > -1) {
1407                         zt_close(cur->subs[SUB_REAL].zfd);
1408                 }
1409                 free(cur);
1410         }
1411         return 0;
1412 }
1413
1414
1415 static int zt_hangup(struct ast_channel *ast)
1416 {
1417         int res;
1418         int index,x, law;
1419         static int restore_gains(struct zt_pvt *p);
1420         struct zt_pvt *p = ast->pvt->pvt;
1421         struct zt_pvt *tmp = NULL;
1422         struct zt_pvt *prev = NULL;
1423         ZT_PARAMS par;
1424
1425         if (option_debug)
1426                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1427         if (!ast->pvt->pvt) {
1428                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1429                 return 0;
1430         }
1431         
1432         ast_pthread_mutex_lock(&p->lock);
1433         
1434         index = zt_get_index(ast, p, 1);
1435
1436         restore_gains(p);
1437         
1438         if (p->dsp)
1439                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
1440
1441         x = 0;
1442         zt_confmute(p, 0);
1443
1444         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1445                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
1446         p->ignoredtmf = 0;
1447         
1448         if (index > -1) {
1449                 /* Real channel, do some fixup */
1450                 p->subs[index].owner = NULL;
1451                 p->subs[index].needanswer = 0;
1452                 p->subs[index].needringing = 0;
1453                 p->subs[index].linear = 0;
1454                 p->subs[index].needcallerid = 0;
1455                 zt_setlinear(p->subs[index].zfd, 0);
1456                 if (index == SUB_REAL) {
1457                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
1458                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
1459                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
1460                                         /* We had flipped over to answer a callwait and now it's gone */
1461                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
1462                                         /* Move to the call-wait, but un-own us until they flip back. */
1463                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1464                                         unalloc_sub(p, SUB_CALLWAIT);
1465                                         p->owner = NULL;
1466                                 } else {
1467                                         /* The three way hung up, but we still have a call wait */
1468                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1469                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
1470                                         unalloc_sub(p, SUB_THREEWAY);
1471                                         if (p->subs[SUB_REAL].inthreeway) {
1472                                                 /* This was part of a three way call.  Immediately make way for
1473                                                    another call */
1474                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1475                                                 p->owner = p->subs[SUB_REAL].owner;
1476                                         } else {
1477                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1478                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1479                                                 p->owner = NULL;
1480                                         }
1481                                         p->subs[SUB_REAL].inthreeway = 0;
1482                                 }
1483                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
1484                                 /* Move to the call-wait and switch back to them. */
1485                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1486                                 unalloc_sub(p, SUB_CALLWAIT);
1487                                 p->owner = p->subs[SUB_REAL].owner;
1488                                 if (p->subs[SUB_REAL].owner->bridge)
1489                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
1490                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
1491                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
1492                                 unalloc_sub(p, SUB_THREEWAY);
1493                                 if (p->subs[SUB_REAL].inthreeway) {
1494                                         /* This was part of a three way call.  Immediately make way for
1495                                            another call */
1496                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1497                                         p->owner = p->subs[SUB_REAL].owner;
1498                                 } else {
1499                                         /* This call hasn't been completed yet...  Set owner to NULL */
1500                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1501                                         p->owner = NULL;
1502                                 }
1503                                 p->subs[SUB_REAL].inthreeway = 0;
1504                         }
1505                 } else if (index == SUB_CALLWAIT) {
1506                         /* Ditch the holding callwait call, and immediately make it availabe */
1507                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1508                                 /* This is actually part of a three way, placed on hold.  Place the third part
1509                                    on music on hold now */
1510                                 if (p->subs[SUB_THREEWAY].owner && p->subs[SUB_THREEWAY].owner->bridge)
1511                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
1512                                 p->subs[SUB_THREEWAY].inthreeway = 0;
1513                                 /* Make it the call wait now */
1514                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
1515                                 unalloc_sub(p, SUB_THREEWAY);
1516                         } else
1517                                 unalloc_sub(p, SUB_CALLWAIT);
1518                 } else if (index == SUB_THREEWAY) {
1519                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1520                                 /* The other party of the three way call is currently in a call-wait state.
1521                                    Start music on hold for them, and take the main guy out of the third call */
1522                                 if (p->subs[SUB_CALLWAIT].owner && p->subs[SUB_CALLWAIT].owner->bridge)
1523                                         ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
1524                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
1525                         }
1526                         p->subs[SUB_REAL].inthreeway = 0;
1527                         /* If this was part of a three way call index, let us make
1528                            another three way call */
1529                         unalloc_sub(p, SUB_THREEWAY);
1530                 } else {
1531                         /* This wasn't any sort of call, but how are we an index? */
1532                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1533                 }
1534         }
1535
1536
1537         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
1538                 p->owner = NULL;
1539                 p->ringt = 0;
1540                 p->distinctivering = 0;
1541                 p->confirmanswer = 0;
1542                 p->cidrings = 1;
1543                 p->outgoing = 0;
1544                 p->digital = 0;
1545                 p->faxhandled = 0;
1546                 p->pulsedial = 0;
1547                 p->onhooktime = time(NULL);
1548                 if (p->dsp) {
1549                         ast_dsp_free(p->dsp);
1550                         p->dsp = NULL;
1551                 }
1552                 law = ZT_LAW_DEFAULT;
1553                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
1554                 if (res < 0) 
1555                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
1556                 /* Perform low level hangup if no owner left */
1557 #ifdef ZAPATA_PRI
1558                 if (p->sig == SIG_PRI) {
1559                         if (p->call) {
1560                                 if (!pri_grab(p->pri)) {
1561                                         res = pri_disconnect(p->pri->pri, p->call, PRI_CAUSE_NORMAL_CLEARING);
1562                                         if (p->alreadyhungup) {
1563                                                 p->call = NULL;
1564                                                 p->alreadyhungup = 0;
1565                                         }
1566                                         if (res < 0) 
1567                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
1568                                         pri_rel(p->pri);                        
1569                                 } else {
1570                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1571                                         res = -1;
1572                                 }
1573                         } else
1574                                 res = 0;
1575
1576                 } else 
1577 #endif
1578 #ifdef ZAPATA_R2
1579                 if (p->sig == SIG_R2) {
1580                         if (p->hasr2call) {
1581                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
1582                                 p->hasr2call = 0;
1583                                 res = 0;
1584                         } else
1585                                 res = 0;
1586
1587                 } else 
1588 #endif
1589                 if (p->sig)
1590                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
1591                 if (res < 0) {
1592                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1593                 }
1594                 switch(p->sig) {
1595                 case SIG_FXOGS:
1596                 case SIG_FXOLS:
1597                 case SIG_FXOKS:
1598                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
1599                         if (!res) {
1600 #if 0
1601                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
1602 #endif
1603                                 /* If they're off hook, try playing congestion */
1604                                 if (par.rxisoffhook)
1605                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
1606                                 else
1607                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1608                         }
1609                         break;
1610                 default:
1611                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1612                 }
1613                 if (p->cidspill)
1614                         free(p->cidspill);
1615                 if (p->sig)
1616                         zt_disable_ec(p);
1617                 x = 0;
1618                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1619                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1620                 p->didtdd = 0;
1621                 p->cidspill = NULL;
1622                 p->callwaitcas = 0;
1623                 p->callwaiting = p->permcallwaiting;
1624                 p->hidecallerid = p->permhidecallerid;
1625                 p->dialing = 0;
1626                 strcpy(p->rdnis, "");
1627                 update_conf(p);
1628                 restart_monitor();
1629         }
1630
1631
1632         p->callwaitingrepeat = 0;
1633         p->cidcwexpire = 0;
1634         ast->pvt->pvt = NULL;
1635         ast_setstate(ast, AST_STATE_DOWN);
1636         ast_pthread_mutex_unlock(&p->lock);
1637         ast_pthread_mutex_lock(&usecnt_lock);
1638         usecnt--;
1639         if (usecnt < 0) 
1640                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1641         ast_pthread_mutex_unlock(&usecnt_lock);
1642         ast_update_use_count();
1643         if (option_verbose > 2) 
1644                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
1645
1646         ast_pthread_mutex_lock(&iflock);
1647         tmp = iflist;
1648         prev = NULL;
1649         if (p->destroy) {
1650                 while (tmp) {
1651                         if (tmp == p) {
1652                                 destroy_channel(prev, tmp, 0);
1653                                 break;
1654                         } else {
1655                                 prev = tmp;
1656                                 tmp = tmp->next;
1657                         }
1658                 }
1659         }
1660         ast_pthread_mutex_unlock(&iflock);
1661         return 0;
1662 }
1663
1664 static int zt_answer(struct ast_channel *ast)
1665 {
1666         struct zt_pvt *p = ast->pvt->pvt;
1667         int res=0;
1668         int index;
1669         int oldstate = ast->_state;
1670         ast_setstate(ast, AST_STATE_UP);
1671         index = zt_get_index(ast, p, 0);
1672         if (index < 0)
1673                 index = SUB_REAL;
1674         /* nothing to do if a radio channel */
1675         if (p->radio)
1676                 return 0;
1677         switch(p->sig) {
1678         case SIG_FXSLS:
1679         case SIG_FXSGS:
1680         case SIG_FXSKS:
1681                 p->ringt = 0;
1682                 /* Fall through */
1683         case SIG_EM:
1684         case SIG_EMWINK:
1685         case SIG_FEATD:
1686         case SIG_FEATDMF:
1687         case SIG_FEATB:
1688         case SIG_SF:
1689         case SIG_SFWINK:
1690         case SIG_SF_FEATD:
1691         case SIG_SF_FEATDMF:
1692         case SIG_SF_FEATB:
1693         case SIG_FXOLS:
1694         case SIG_FXOGS:
1695         case SIG_FXOKS:
1696                 /* Pick up the line */
1697                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
1698                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
1699                 tone_zone_play_tone(p->subs[index].zfd, -1);
1700                 p->dialing = 0;
1701                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
1702                         if (oldstate == AST_STATE_RINGING) {
1703                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
1704                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
1705                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
1706                                 p->owner = p->subs[SUB_REAL].owner;
1707                         }
1708                 }
1709                 break;
1710 #ifdef ZAPATA_PRI
1711         case SIG_PRI:
1712                 /* Send a pri acknowledge */
1713                 if (!pri_grab(p->pri)) {
1714                         res = pri_answer(p->pri->pri, p->call, 0, 1);
1715                         pri_rel(p->pri);
1716                 } else {
1717                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1718                         res= -1;
1719                 }
1720                 break;
1721 #endif
1722 #ifdef ZAPATA_R2
1723         case SIG_R2:
1724                 res = mfcr2_AnswerCall(p->r2, NULL);
1725                 if (res)
1726                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
1727                 break;
1728 #endif                  
1729         case 0:
1730                 return 0;
1731         default:
1732                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1733                 return -1;
1734         }
1735         return res;
1736 }
1737
1738 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
1739 {
1740 char    *cp;
1741 int     x;
1742
1743         struct zt_pvt *p = chan->pvt->pvt;
1744
1745         
1746         if ((option != AST_OPTION_TONE_VERIFY) &&
1747                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
1748            {
1749                 errno = ENOSYS;
1750                 return -1;
1751            }
1752         cp = (char *)data;
1753         if ((!cp) || (datalen < 1))
1754            {
1755                 errno = EINVAL;
1756                 return -1;
1757            }
1758         switch(option) {
1759             case AST_OPTION_TONE_VERIFY:
1760                 if (!p->dsp)
1761                         break;
1762                 switch(*cp) {
1763                     case 1:
1764                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
1765                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
1766                         break;
1767                     case 2:
1768                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
1769                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
1770                         break;
1771                     default:
1772                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
1773                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
1774                         break;
1775                 }
1776                 break;
1777             case AST_OPTION_TDD:  /* turn on or off TDD */
1778                 if (!*cp) { /* turn it off */
1779                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
1780                         if (p->tdd) tdd_free(p->tdd);
1781                         p->tdd = 0;
1782                         p->mate = 0;
1783                         break;
1784                 }
1785                 if (*cp == 2)
1786                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
1787                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
1788                 p->mate = 0;
1789                 zt_disable_ec(p);
1790                 /* otherwise, turn it on */
1791                 if (!p->didtdd) { /* if havent done it yet */
1792                         unsigned char mybuf[41000],*buf;
1793                         int size,res,fd,len;
1794                         int index;
1795                         fd_set wfds,efds;
1796                         buf = mybuf;
1797                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
1798                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
1799                         len = 40000;
1800                         index = zt_get_index(chan, p, 0);
1801                         if (index < 0) {
1802                                 ast_log(LOG_WARNING, "No index in TDD?\n");
1803                                 return -1;
1804                         }
1805                         fd = p->subs[index].zfd;
1806                         while(len) {
1807                                 if (ast_check_hangup(chan)) return -1;
1808                                 size = len;
1809                                 if (size > READ_SIZE)
1810                                         size = READ_SIZE;
1811                                 FD_ZERO(&wfds);
1812                                 FD_ZERO(&efds);
1813                                 FD_SET(fd,&wfds);
1814                                 FD_SET(fd,&efds);                       
1815                                 res = select(fd + 1,NULL,&wfds,&efds,NULL);
1816                                 if (!res) {
1817                                         ast_log(LOG_DEBUG, "select (for write) ret. 0 on channel %d\n", p->channel);
1818                                         continue;
1819                                 }
1820                                   /* if got exception */
1821                                 if (FD_ISSET(fd,&efds)) return -1;
1822                                 if (!FD_ISSET(fd,&wfds)) {
1823                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
1824                                         continue;
1825                                 }
1826                                 res = write(fd, buf, size);
1827                                 if (res != size) {
1828                                         if (res == -1) return -1;
1829                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
1830                                         break;
1831                                 }
1832                                 len -= size;
1833                                 buf += size;
1834                         }
1835                         p->didtdd = 1; /* set to have done it now */            
1836                 }
1837                 if (*cp == 2) { /* Mate mode */
1838                         if (p->tdd) tdd_free(p->tdd);
1839                         p->tdd = 0;
1840                         p->mate = 1;
1841                         break;
1842                         }               
1843                 if (!p->tdd) { /* if we dont have one yet */
1844                         p->tdd = tdd_new(); /* allocate one */
1845                 }               
1846                 break;
1847             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
1848                 if (!*cp)
1849                 {               
1850                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
1851                         x = 0;
1852                 }
1853                 else
1854                 {               
1855                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
1856                         x = 1;
1857                 }
1858                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
1859                 break;
1860         }
1861         errno = 0;
1862         return 0;
1863 }
1864
1865 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master)
1866 {
1867         /* Unlink a specific slave or all slaves/masters from a given master */
1868         int x;
1869         int hasslaves;
1870         if (!master)
1871                 return;
1872         hasslaves = 0;
1873         for (x=0;x<MAX_SLAVES;x++) {
1874                 if (master->slaves[x]) {
1875                         if (!slave || (master->slaves[x] == slave)) {
1876                                 /* Take slave out of the conference */
1877                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
1878                                 conf_del(&master->confno, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
1879                                 master->slaves[x]->master = NULL;
1880                                 master->slaves[x] = NULL;
1881                         } else
1882                                 hasslaves = 1;
1883                 }
1884                 if (!hasslaves)
1885                         master->inconference = 0;
1886         }
1887         if (!slave) {
1888                 if (master->master) {
1889                         /* Take master out of the conference */
1890                         conf_del(&master->master->confno, &master->subs[SUB_REAL], SUB_REAL);
1891                         hasslaves = 0;
1892                         for (x=0;x<MAX_SLAVES;x++) {
1893                                 if (master->master->slaves[x] == master)
1894                                         master->master->slaves[x] = NULL;
1895                                 else if (master->master->slaves[x])
1896                                         hasslaves = 1;
1897                         }
1898                         if (!hasslaves)
1899                                 master->master->inconference = 0;
1900                 }
1901                 master->master = NULL;
1902         }
1903         update_conf(master);
1904 }
1905
1906 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
1907         int x;
1908         if (!slave || !master) {
1909                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
1910                 return;
1911         }
1912         for (x=0;x<MAX_SLAVES;x++) {
1913                 if (!master->slaves[x]) {
1914                         master->slaves[x] = slave;
1915                         break;
1916                 }
1917         }
1918         if (x >= MAX_SLAVES) {
1919                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
1920                 master->slaves[MAX_SLAVES - 1] = slave;
1921         }
1922         if (slave->master) 
1923                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
1924         slave->master = master;
1925         
1926         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
1927 }
1928
1929 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1930 {
1931         struct ast_channel *who = NULL, *cs[3];
1932         struct zt_pvt *p0, *p1, *op0, *op1;
1933         struct zt_pvt *master=NULL, *slave=NULL;
1934         struct ast_frame *f;
1935         int to;
1936         int inconf = 0;
1937         int nothingok = 0;
1938         int ofd1, ofd2;
1939         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
1940         int os1 = -1, os2 = -1;
1941         struct ast_channel *oc1, *oc2;
1942
1943         /* if need DTMF, cant native bridge */
1944         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1945                 return -2;
1946         p0 = c0->pvt->pvt;
1947         p1 = c1->pvt->pvt;
1948         /* cant do pseudo-channels here */
1949         if ((!p0->sig) || (!p1->sig)) return -2;
1950
1951         ast_pthread_mutex_lock(&c0->lock);
1952         ast_pthread_mutex_lock(&c1->lock);
1953         op0 = p0 = c0->pvt->pvt;
1954         op1 = p1 = c1->pvt->pvt;
1955         ofd1 = c0->fds[0];
1956         ofd2 = c1->fds[0];
1957         oi1 = zt_get_index(c0, p0, 0);
1958         oi2 = zt_get_index(c1, p1, 0);
1959         oc1 = p0->owner;
1960         oc2 = p1->owner;
1961         if ((oi1 < 0) || (oi2 < 0))
1962                 return -1;
1963
1964
1965
1966         ast_pthread_mutex_lock(&p0->lock);
1967         if (pthread_mutex_trylock(&p1->lock)) {
1968                 /* Don't block, due to potential for deadlock */
1969                 ast_pthread_mutex_unlock(&p0->lock);
1970                 ast_pthread_mutex_unlock(&c0->lock);
1971                 ast_pthread_mutex_unlock(&c1->lock);
1972                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
1973                 return -3;
1974         }
1975         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
1976                 if (!p0->owner || !p1->owner) {
1977                         /* Currently unowned -- Do nothing.  */
1978                         nothingok = 1;
1979                 } else {
1980                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
1981                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
1982                                 master = p0;
1983                                 slave = p1;
1984                                 inconf = 1;
1985                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
1986                                 master = p1;
1987                                 slave = p0;
1988                                 inconf = 1;
1989                         } else {
1990                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
1991                                 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,
1992                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
1993                         }
1994                 }
1995         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
1996                 if (p1->subs[SUB_THREEWAY].inthreeway) {
1997                         master = p1;
1998                         slave = p0;
1999                 } else {
2000                         nothingok = 1;
2001                 }
2002         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2003                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2004                         master = p0;
2005                         slave = p1;
2006                 } else {
2007                         nothingok  = 1;
2008                 }
2009         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2010                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2011                    don't put us in anything */
2012                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2013                         master = p1;
2014                         slave = p0;
2015                 } else {
2016                         nothingok = 1;
2017                 }
2018         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2019                 /* Same as previous */
2020                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2021                         master = p0;
2022                         slave = p1;
2023                 } else {
2024                         nothingok = 1;
2025                 }
2026         }
2027         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2028                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2029         if (master && slave) {
2030                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2031                    in an active threeway call with a channel that is ringing, we should
2032                    indicate ringing. */
2033                 if ((oi2 == SUB_THREEWAY) && 
2034                         p1->subs[SUB_THREEWAY].inthreeway && 
2035                         p1->subs[SUB_REAL].owner && 
2036                         p1->subs[SUB_REAL].inthreeway && 
2037                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2038                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2039                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2040                                 os2 = p1->subs[SUB_REAL].owner->_state;
2041                 } else {
2042                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2043                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2044                 }
2045                 if ((oi1 == SUB_THREEWAY) && 
2046                         p0->subs[SUB_THREEWAY].inthreeway && 
2047                         p0->subs[SUB_REAL].owner && 
2048                         p0->subs[SUB_REAL].inthreeway && 
2049                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2050                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2051                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2052                                 os1 = p0->subs[SUB_REAL].owner->_state;
2053                 } else {
2054                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2055                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2056                 }
2057                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2058                         if (!p0->echocanbridged || !p1->echocanbridged) {
2059                                 /* Disable echo cancellation if appropriate */
2060                                 zt_disable_ec(p0);
2061                                 zt_disable_ec(p1);
2062                         }
2063                 }
2064                 zt_link(slave, master);
2065                 master->inconference = inconf;
2066         } else if (!nothingok)
2067                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2068
2069         update_conf(p0);
2070         update_conf(p1);
2071         t1 = p0->subs[SUB_REAL].inthreeway;
2072         t2 = p1->subs[SUB_REAL].inthreeway;
2073
2074         ast_pthread_mutex_unlock(&p0->lock);
2075         ast_pthread_mutex_unlock(&p1->lock);
2076
2077         ast_pthread_mutex_unlock(&c0->lock);
2078         ast_pthread_mutex_unlock(&c1->lock);
2079
2080         /* Native bridge failed */
2081         if ((!master || !slave) && !nothingok) {
2082                 if (op0 == p0)
2083                         zt_enable_ec(p0);
2084                 if (op1 == p1)
2085                         zt_enable_ec(p1);
2086                 return -1;
2087         }
2088         
2089         cs[0] = c0;
2090         cs[1] = c1;
2091         cs[2] = NULL;
2092         for (;;) {
2093                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2094                    and then balking if anything is wrong */
2095                 ast_pthread_mutex_lock(&c0->lock);
2096                 ast_pthread_mutex_lock(&c1->lock);
2097                 p0 = c0->pvt->pvt;
2098                 p1 = c1->pvt->pvt;
2099                 if (op0 == p0)
2100                         i1 = zt_get_index(c0, p0, 1);
2101                 if (op1 == p1)
2102                         i2 = zt_get_index(c1, p1, 1);
2103                 ast_pthread_mutex_unlock(&c0->lock);
2104                 ast_pthread_mutex_unlock(&c1->lock);
2105                 if ((op0 != p0) || (op1 != p1) || 
2106                     (ofd1 != c0->fds[0]) || 
2107                         (ofd2 != c1->fds[0]) ||
2108                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2109                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2110                     (oc1 != p0->owner) || 
2111                         (oc2 != p1->owner) ||
2112                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2113                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2114                         (oi1 != i1) ||
2115                         (oi2 != i2)) {
2116                         if (slave && master)
2117                                 zt_unlink(slave, master);
2118                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2119                                                                         op0->channel, oi1, op1->channel, oi2);
2120                         if (op0 == p0)
2121                                 zt_enable_ec(p0);
2122                         if (op1 == p1)
2123                                 zt_enable_ec(p1);
2124                         return -3;
2125                 }
2126                 to = -1;
2127                 who = ast_waitfor_n(cs, 2, &to);
2128                 if (!who) {
2129                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2130                         continue;
2131                 }
2132                 if (who->pvt->pvt == op0) 
2133                         op0->ignoredtmf = 1;
2134                 else if (who->pvt->pvt == op1)
2135                         op1->ignoredtmf = 1;
2136                 f = ast_read(who);
2137                 if (who->pvt->pvt == op0) 
2138                         op0->ignoredtmf = 0;
2139                 else if (who->pvt->pvt == op1)
2140                         op1->ignoredtmf = 0;
2141                 if (!f) {
2142                         *fo = NULL;
2143                         *rc = who;
2144                         if (slave && master)
2145                                 zt_unlink(slave, master);
2146                         if (op0 == p0)
2147                                 zt_enable_ec(p0);
2148                         if (op1 == p1)
2149                                 zt_enable_ec(p1);
2150                         return 0;
2151                 }
2152                 if (f->frametype == AST_FRAME_DTMF) {
2153                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2154                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2155                                 *fo = f;
2156                                 *rc = who;
2157                                 if (slave && master)
2158                                         zt_unlink(slave, master);
2159                                 return 0;
2160                         } else if ((who == c0) && p0->pulsedial) {
2161                                 ast_write(c1, f);
2162                         } else if ((who == c1) && p1->pulsedial) {
2163                                 ast_write(c0, f);
2164                         }
2165                 }
2166                 ast_frfree(f);
2167
2168                 /* Swap who gets priority */
2169                 cs[2] = cs[0];
2170                 cs[0] = cs[1];
2171                 cs[1] = cs[2];
2172         }
2173 }
2174
2175 static int zt_indicate(struct ast_channel *chan, int condition);
2176
2177 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2178 {
2179         struct zt_pvt *p = newchan->pvt->pvt;
2180         int x;
2181         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2182         if (p->owner == oldchan)
2183                 p->owner = newchan;
2184         for (x=0;x<3;x++)
2185                 if (p->subs[x].owner == oldchan) {
2186                         if (!x)
2187                                 zt_unlink(NULL, p);
2188                         p->subs[x].owner = newchan;
2189                 }
2190         if (newchan->_state == AST_STATE_RINGING) 
2191                 zt_indicate(newchan, AST_CONTROL_RINGING);
2192         update_conf(p);
2193         return 0;
2194 }
2195
2196 static int zt_ring_phone(struct zt_pvt *p)
2197 {
2198         int x;
2199         int res;
2200         /* Make sure our transmit state is on hook */
2201         x = 0;
2202         x = ZT_ONHOOK;
2203         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2204         do {
2205                 x = ZT_RING;
2206                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2207 #if 0
2208                 printf("Res: %d, error: %s\n", res, strerror(errno));
2209 #endif                                          
2210                 if (res) {
2211                         switch(errno) {
2212                         case EBUSY:
2213                         case EINTR:
2214                                 /* Wait just in case */
2215                                 usleep(10000);
2216                                 continue;
2217                         case EINPROGRESS:
2218                                 res = 0;
2219                                 break;
2220                         default:
2221                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2222                                 res = 0;
2223                         }
2224                 }
2225         } while (res);
2226         return res;
2227 }
2228
2229 static void *ss_thread(void *data);
2230
2231 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int);
2232
2233 static int attempt_transfer(struct zt_pvt *p)
2234 {
2235         /* In order to transfer, we need at least one of the channels to
2236            actually be in a call bridge.  We can't conference two applications
2237            together (but then, why would we want to?) */
2238         if (p->subs[SUB_REAL].owner->bridge) {
2239                 /* The three-way person we're about to transfer to could still be in MOH, so
2240                    stop if now if appropriate */
2241                 if (p->subs[SUB_THREEWAY].owner->bridge)
2242                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2243                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2244                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2245                 }
2246                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2247                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2248                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2249                         return -1;
2250                 }
2251                 /* Orphan the channel */
2252                 unalloc_sub(p, SUB_THREEWAY);
2253         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2254                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2255                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2256                 }
2257                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2258                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2259                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2260                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2261                         return -1;
2262                 }
2263                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2264                 unalloc_sub(p, SUB_THREEWAY);
2265                 /* Tell the caller not to hangup */
2266                 return 1;
2267         } else {
2268                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2269                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2270                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2271         }
2272         return 0;
2273 }
2274
2275 #ifdef ZAPATA_R2
2276 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2277 {
2278         struct ast_frame *f;
2279         f = &p->subs[index].f;
2280         if (!p->r2) {
2281                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2282                 return NULL;
2283         }
2284         switch(e->e) {
2285         case MFCR2_EVENT_BLOCKED:
2286                 if (option_verbose > 2)
2287                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2288                 break;
2289         case MFCR2_EVENT_UNBLOCKED:
2290                 if (option_verbose > 2)
2291                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2292                 break;
2293         case MFCR2_EVENT_CONFIG_ERR:
2294                 if (option_verbose > 2)
2295                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2296                 break;
2297         case MFCR2_EVENT_RING:
2298                 if (option_verbose > 2)
2299                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2300                 break;
2301         case MFCR2_EVENT_HANGUP:
2302                 if (option_verbose > 2)
2303                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2304                 break;
2305         case MFCR2_EVENT_RINGING:
2306                 if (option_verbose > 2)
2307                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2308                 break;
2309         case MFCR2_EVENT_ANSWER:
2310                 if (option_verbose > 2)
2311                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2312                 break;
2313         case MFCR2_EVENT_HANGUP_ACK:
2314                 if (option_verbose > 2)
2315                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2316                 break;
2317         case MFCR2_EVENT_IDLE:
2318                 if (option_verbose > 2)
2319                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2320                 break;
2321         default:
2322                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2323                 break;
2324         }
2325         return f;
2326 }
2327
2328 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2329 {
2330         int x;
2331         int res;
2332         mfcr2_event_t *e;
2333         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2334         if (res) {
2335                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2336                 return NULL;
2337         }
2338         if (!p->r2) {
2339                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2340                 return NULL;
2341         }
2342         e = mfcr2_cas_signaling_event(p->r2, x);
2343         return e;
2344 }
2345 #endif
2346
2347 static int check_for_conference(struct zt_pvt *p)
2348 {
2349         ZT_CONFINFO ci;
2350         /* Fine if we already have a master, etc */
2351         if (p->master || (p->confno > -1))
2352                 return 0;
2353         memset(&ci, 0, sizeof(ci));
2354         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2355                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2356                 return 0;
2357         }
2358         /* If we have no master and don't have a confno, then 
2359            if we're in a conference, it's probably a MeetMe room or
2360            some such, so don't let us 3-way out! */
2361         if (ci.confno) {
2362                 if (option_verbose > 2) 
2363                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2364                 return 1;
2365         }
2366         return 0;
2367 }
2368
2369 static int get_alarms(struct zt_pvt *p)
2370 {
2371         int res;
2372         ZT_SPANINFO zi;
2373         memset(&zi, 0, sizeof(zi));
2374         zi.spanno = p->span;
2375         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2376         if (res < 0) {
2377                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2378                 return 0;
2379         }
2380         return zi.alarms;
2381 }
2382                         
2383 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2384 {
2385         int res,x;
2386         int index;
2387         struct zt_pvt *p = ast->pvt->pvt;
2388         pthread_t threadid;
2389         pthread_attr_t attr;
2390         struct ast_channel *chan;
2391         pthread_attr_init(&attr);
2392         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2393         index = zt_get_index(ast, p, 0);
2394         p->subs[index].f.frametype = AST_FRAME_NULL;
2395         p->subs[index].f.datalen = 0;
2396         p->subs[index].f.samples = 0;
2397         p->subs[index].f.mallocd = 0;
2398         p->subs[index].f.offset = 0;
2399         p->subs[index].f.src = "zt_handle_event";
2400         p->subs[index].f.data = NULL;
2401         if (index < 0)
2402                 return &p->subs[index].f;
2403         res = zt_get_event(p->subs[index].zfd);
2404         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
2405         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFDIGIT)) {
2406                 if (res & ZT_EVENT_PULSEDIGIT)
2407                         p->pulsedial = 1;
2408                 else
2409                         p->pulsedial = 0;
2410                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
2411                 p->subs[index].f.frametype = AST_FRAME_DTMF;
2412                 p->subs[index].f.subclass = res & 0xff;
2413                 /* Return the captured digit */
2414                 return &p->subs[index].f;
2415         }
2416         switch(res) {
2417                 case ZT_EVENT_BITSCHANGED:
2418                         if (p->sig == SIG_R2) {
2419 #ifdef ZAPATA_R2
2420                                 struct ast_frame  *f = &p->subs[index].f;
2421                                 mfcr2_event_t *e;
2422                                 e = r2_get_event_bits(p);
2423                                 if (e)
2424                                         f = handle_r2_event(p, e, index);
2425                                 return f;
2426 #else                           
2427                                 break;
2428 #endif
2429                         }
2430                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
2431                 case ZT_EVENT_PULSE_START:
2432                         /* Stop tone if there's a pulse start and the PBX isn't started */
2433                         if (!ast->pbx)
2434                                 tone_zone_play_tone(p->subs[index].zfd, -1);
2435                         break;  
2436                 case ZT_EVENT_DIALCOMPLETE:
2437                         if (p->inalarm) break;
2438                         if (p->radio) break;
2439                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
2440                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
2441                                 return NULL;
2442                         }
2443                         if (!x) { /* if not still dialing in driver */
2444                                 zt_enable_ec(p);
2445                                 p->dialing = 0;
2446                                 if (ast->_state == AST_STATE_DIALING) {
2447                                         if (p->callprogress && CANPROGRESSDETECT(p) && p->dsp) {
2448                                                 ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
2449                                         } 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)))) {
2450                                                 ast_setstate(ast, AST_STATE_RINGING);
2451                                         } else {
2452                                                 ast_setstate(ast, AST_STATE_UP);
2453                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2454                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2455                                         }
2456                                 }
2457                         }
2458                         break;
2459                 case ZT_EVENT_ALARM:
2460                         p->inalarm = 1;
2461                         res = get_alarms(p);
2462                         ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
2463                         /* fall through intentionally */
2464                 case ZT_EVENT_ONHOOK:
2465                         if (p->radio)
2466                         {
2467                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2468                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
2469                                 break;
2470                         }
2471                         switch(p->sig) {
2472                         case SIG_FXOLS:
2473                         case SIG_FXOGS:
2474                         case SIG_FXOKS:
2475                                 p->onhooktime = time(NULL);
2476                                 p->msgstate = -1;
2477                                 /* Check for some special conditions regarding call waiting */
2478                                 if (index == SUB_REAL) {
2479                                         /* The normal line was hung up */
2480                                         if (p->subs[SUB_CALLWAIT].owner) {
2481                                                 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2482                                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2483                                                 if (option_verbose > 2) 
2484                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2485                                                 unalloc_sub(p, SUB_CALLWAIT);   
2486 #if 0
2487                                                 p->subs[index].needanswer = 0;
2488                                                 p->subs[index].needringing = 0;
2489 #endif                                          
2490                                                 p->callwaitingrepeat = 0;
2491                                                 p->cidcwexpire = 0;
2492                                                 p->owner = NULL;
2493                                                 zt_ring_phone(p);
2494                                         } else if (p->subs[SUB_THREEWAY].owner) {
2495                                                 struct timeval tv;
2496                                                 unsigned int mssinceflash;
2497                                                 gettimeofday(&tv, NULL);
2498                                                 mssinceflash = (tv.tv_sec - p->flashtime.tv_sec) * 1000 + (tv.tv_usec - p->flashtime.tv_usec) / 1000;
2499                                                 if (mssinceflash < MIN_MS_SINCE_FLASH) {
2500                                                         /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
2501                                                            hanging up.  Hangup both channels now */
2502                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2503                                                         ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2504                                                 } else if ((ast->pbx) ||
2505                                                         (ast->_state == AST_STATE_UP)) {
2506                                                         if (p->transfer) {
2507                                                                 /* In any case this isn't a threeway call anymore */
2508                                                                 p->subs[SUB_REAL].inthreeway = 0;
2509                                                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2510                                                                 if ((res = attempt_transfer(p)) < 0)
2511                                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2512                                                                 else if (res) {
2513                                                                         /* Don't actually hang up at this point */
2514                                                                         break;
2515                                                                 }
2516                                                         } else
2517                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2518                                                 } else {
2519                                                         /* Swap subs and dis-own channel */
2520                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2521                                                         p->owner = NULL;
2522                                                         /* Ring the phone */
2523                                                         zt_ring_phone(p);
2524                                                 }
2525                                         }
2526                                 } else {
2527                                         ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
2528                                 }
2529                                 /* Fall through */
2530                         default:
2531                                 zt_disable_ec(p);
2532                                 return NULL;
2533                         }
2534                         break;
2535                 case ZT_EVENT_RINGOFFHOOK:
2536                         if (p->inalarm) break;
2537                         if (p->radio)
2538                         {
2539                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2540                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
2541                                 break;
2542                         }
2543                         switch(p->sig) {
2544                         case SIG_FXOLS:
2545                         case SIG_FXOGS:
2546                         case SIG_FXOKS:
2547                                 switch(ast->_state) {
2548                                 case AST_STATE_RINGING:
2549                                         zt_enable_ec(p);
2550                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2551                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2552                                         /* Make sure it stops ringing */
2553                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
2554                                         ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
2555                                         if (p->cidspill) {
2556                                                 /* Cancel any running CallerID spill */
2557                                                 free(p->cidspill);
2558                                                 p->cidspill = NULL;
2559                                         }
2560                                         p->dialing = 0;
2561                                         p->callwaitcas = 0;
2562                                         if (p->confirmanswer) {
2563                                                 /* Ignore answer if "confirm answer" is selected */
2564                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2565                                                 p->subs[index].f.subclass = 0;
2566                                         } else 
2567                                                 ast_setstate(ast, AST_STATE_UP);
2568                                         return &p->subs[index].f;
2569                                 case AST_STATE_DOWN:
2570                                         ast_setstate(ast, AST_STATE_RING);
2571                                         ast->rings = 1;
2572                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2573                                         p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
2574                                         ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
2575                                         return &p->subs[index].f;
2576                                 case AST_STATE_UP:
2577                                         /* Make sure it stops ringing */
2578                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
2579                                         /* Okay -- probably call waiting*/
2580                                         if (p->owner->bridge)
2581                                                         ast_moh_stop(p->owner->bridge);
2582                                         break;
2583                                 default:
2584                                         ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
2585                                 }
2586                                 break;
2587                         case SIG_FXSLS:
2588                         case SIG_FXSGS:
2589                         case SIG_FXSKS:
2590                                 if (ast->_state == AST_STATE_RING) {
2591                                         p->ringt = RINGT;
2592                                 }
2593                                 /* Fall through */
2594                         case SIG_EM:
2595                         case SIG_EMWINK:
2596                         case SIG_FEATD:
2597                         case SIG_FEATDMF:
2598                         case SIG_FEATB:
2599                         case SIG_SF:
2600                         case SIG_SFWINK:
2601                         case SIG_SF_FEATD:
2602                         case SIG_SF_FEATDMF:
2603                         case SIG_SF_FEATB:
2604                                 if (ast->_state == AST_STATE_DOWN) {
2605                                         if (option_debug)
2606                                                 ast_log(LOG_DEBUG, "Ring detected\n");
2607                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2608                                         p->subs[index].f.subclass = AST_CONTROL_RING;
2609                                 } else if (ast->_state == AST_STATE_RINGING) {
2610                                         if (option_debug)
2611                                                 ast_log(LOG_DEBUG, "Line answered\n");
2612                                         if (p->confirmanswer) {
2613                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2614                                                 p->subs[index].f.subclass = 0;
2615                                         } else {
2616                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2617                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2618                                                 ast_setstate(ast, AST_STATE_UP);
2619                                         }
2620                                 } else if (ast->_state != AST_STATE_RING)
2621                                         ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
2622                                 break;
2623                         default:
2624                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
2625                         }
2626                         break;
2627                 case ZT_EVENT_RINGEROFF:
2628                         if (p->inalarm) break;
2629                         if (p->radio) break;
2630                         ast->rings++;
2631                         if ((ast->rings > p->cidrings) && (p->cidspill)) {
2632                                 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
2633                                 free(p->cidspill);
2634                                 p->cidspill = NULL;
2635                                 p->callwaitcas = 0;
2636                         }
2637                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2638                         p->subs[index].f.subclass = AST_CONTROL_RINGING;
2639                         break;
2640                 case ZT_EVENT_RINGERON:
2641                         break;
2642                 case ZT_EVENT_NOALARM:
2643                         p->inalarm = 0;
2644                         ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
2645                         break;
2646                 case ZT_EVENT_WINKFLASH:
2647                         if (p->inalarm) break;
2648                         if (p->radio) break;
2649                         /* Remember last time we got a flash-hook */
2650                         gettimeofday(&p->flashtime, NULL);
2651                         switch(p->sig) {
2652                         case SIG_FXOLS:
2653                         case SIG_FXOGS:
2654                         case SIG_FXOKS:
2655                                 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
2656                                         index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2657                                 p->callwaitcas = 0;
2658                                 if (index == SUB_REAL) {
2659                                         if (p->subs[SUB_CALLWAIT].owner) {
2660                                                 /* Swap to call-wait */
2661                                                 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
2662                                                 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2663                                                 p->owner = p->subs[SUB_REAL].owner;
2664                                                 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
2665                                                 if (p->owner->_state == AST_STATE_RINGING) {
2666                                                         ast_setstate(p->owner, AST_STATE_UP);
2667                                                         p->subs[SUB_REAL].needanswer = 1;
2668                                                 }
2669                                                 p->callwaitingrepeat = 0;
2670                                                 p->cidcwexpire = 0;
2671                                                 /* Start music on hold if appropriate */
2672                                                 if (!p->subs[SUB_CALLWAIT].inthreeway && p->subs[SUB_CALLWAIT].owner->bridge)
2673                                                                 ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
2674                                                 if (p->subs[SUB_REAL].owner->bridge)
2675                                                                 ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
2676                                         } else if (!p->subs[SUB_THREEWAY].owner) {
2677                                                 if (p->threewaycalling && !check_for_conference(p)) {
2678                                                         /* XXX This section needs much more error checking!!! XXX */
2679                                                         /* Start a 3-way call if feasible */
2680                                                         if ((ast->pbx) ||
2681                                                                         (ast->_state == AST_STATE_UP) ||
2682                                                                         (ast->_state == AST_STATE_RING)) {
2683                                                                 if (!alloc_sub(p, SUB_THREEWAY)) {
2684                                                                         /* Make new channel */
2685                                                                         chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0);
2686                                                                         /* Swap things around between the three-way and real call */
2687                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2688                                                                         /* Disable echo canceller for better dialing */
2689                                                                         zt_disable_ec(p);
2690                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
2691                                                                         if (res)
2692                                                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
2693                                                                         p->owner = chan;
2694                                                                         if (pthread_create(&threadid, &attr, ss_thread, chan)) {
2695                                                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
2696                                                                                 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2697                                                                                 zt_enable_ec(p);
2698                                                                                 ast_hangup(chan);
2699                                                                         } else {
2700                                                                                 if (option_verbose > 2) 
2701                                                                                         ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
2702                                                                                 /* Start music on hold if appropriate */
2703                                                                                 if (p->subs[SUB_THREEWAY].owner->bridge)
2704                                                                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
2705                                                                         }               
2706                                                                 } else
2707                                                                         ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
2708                                                         } else 
2709                                                                 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
2710                                                 }
2711                                         } else {
2712                                                 /* Already have a 3 way call */
2713                                                 if (p->subs[SUB_THREEWAY].inthreeway) {
2714                                                         /* Call is already up, drop the last person */
2715                                                         if (option_debug)
2716                                                                 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
2717                                                         /* If the primary call isn't answered yet, use it */
2718                                                         if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
2719                                                                 /* Swap back -- we're droppign the real 3-way that isn't finished yet*/
2720                                                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2721                                                                 p->owner = p->subs[SUB_REAL].owner;
2722                                                         }
2723                                                         /* Drop the last call and stop the conference */
2724                                                         if (option_verbose > 2)
2725                                                                 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
2726                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2727                                                         p->subs[SUB_REAL].inthreeway = 0;
2728                                                         p->subs[SUB_THREEWAY].inthreeway = 0;
2729                                                 } else {
2730                                                         /* Lets see what we're up to */
2731                                                         if ((ast->pbx) ||
2732                                                                         (ast->_state == AST_STATE_UP)) {
2733                                                                 int otherindex = SUB_THREEWAY;
2734                                                                 if (option_verbose > 2)
2735                                                                         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);
2736                                                                 /* Put them in the threeway, and flip */
2737                                                                 p->subs[SUB_THREEWAY].inthreeway = 1;
2738                                                                 p->subs[SUB_REAL].inthreeway = 1;
2739                                                                 if (ast->_state == AST_STATE_UP) {
2740                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2741                                                                         otherindex = SUB_REAL;
2742                                                                 }
2743                                                                 if (p->subs[otherindex].owner && p->subs[otherindex].owner->bridge)
2744                                                                         ast_moh_stop(p->subs[otherindex].owner->bridge);
2745                                                                 p->owner = p->subs[SUB_REAL].owner;
2746                                                                 if (ast->_state == AST_STATE_RINGING) {
2747                                                                         ast_log(LOG_DEBUG, "Enabling ringtone on real and threeway\n");
2748                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_RINGTONE);
2749                                                                         res = tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, ZT_TONE_RINGTONE);
2750                                                                 }
2751                                                         } else {
2752                                                                 if (option_verbose > 2)
2753                                                                         ast_verbose(VERBOSE_PREFIX_3 "Dumping incomplete call on on %s\n", p->subs[SUB_THREEWAY].owner->name);
2754                                                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2755                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2756                                                                 p->owner = p->subs[SUB_REAL].owner;
2757                                                                 if (p->subs[SUB_REAL].owner && p->subs[SUB_REAL].owner->bridge)
2758                                                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
2759                                                                 zt_enable_ec(p);
2760                                                         }
2761                                                         
2762                                                 }
2763                                         }
2764                                 } else {
2765                                         ast_log(LOG_WARNING, "Got flash hook with index %d on channel %d?!?\n", index, p->channel);
2766                                 }
2767                                 update_conf(p);
2768                                 break;
2769                         case SIG_EM:
2770                         case SIG_EMWINK:
2771                         case SIG_FEATD:
2772                         case SIG_SF:
2773                         case SIG_SFWINK:
2774                         case SIG_SF_FEATD:
2775                         case SIG_FXSLS:
2776                         case SIG_FXSGS:
2777                                 if (p->dialing)
2778                                         ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
2779                                 else
2780                                         ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
2781                                 break;
2782                         case SIG_FEATDMF:
2783                         case SIG_FEATB:
2784                         case SIG_SF_FEATDMF:
2785                         case SIG_SF_FEATB:
2786                                 /* FGD MF *Must* wait for wink */
2787                                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2788                                 if (res < 0) {
2789                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
2790                                         p->dop.dialstr[0] = '\0';
2791                                         return NULL;
2792                                 } else 
2793                                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
2794                                 p->dop.dialstr[0] = '\0';
2795                                 break;
2796                         default:
2797                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
2798                         }
2799                         break;
2800                 case ZT_EVENT_HOOKCOMPLETE:
2801                         if (p->inalarm) break;
2802                         if (p->radio) break;
2803                         switch(p->sig) {
2804                         case SIG_FXSLS:  /* only interesting for FXS */
2805                         case SIG_FXSGS:
2806                         case SIG_FXSKS:
2807                         case SIG_EM:
2808                         case SIG_EMWINK:
2809                         case SIG_FEATD:
2810                         case SIG_SF:
2811                         case SIG_SFWINK:
2812                         case SIG_SF_FEATD:
2813