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