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