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