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