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