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