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