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