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