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