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