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