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