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