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