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