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