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