Fix answeronpolarityswitch and hanguponpolarityswitch when both are yes (#6229)
[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         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1663                 return -1;
1664         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1665         /* Make sure we account for the end */
1666         p->cidlen += READ_SIZE * 4;
1667         p->cidpos = 0;
1668         send_callerid(p);
1669         if (option_verbose > 2)
1670                 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1671         return 0;
1672 }
1673
1674 static int has_voicemail(struct zt_pvt *p)
1675 {
1676
1677         return ast_app_has_voicemail(p->mailbox, NULL);
1678 }
1679
1680 static int send_callerid(struct zt_pvt *p)
1681 {
1682         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1683         int res;
1684         /* Take out of linear mode if necessary */
1685         if (p->subs[SUB_REAL].linear) {
1686                 p->subs[SUB_REAL].linear = 0;
1687                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1688         }
1689         while(p->cidpos < p->cidlen) {
1690                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1691                 if (res < 0) {
1692                         if (errno == EAGAIN)
1693                                 return 0;
1694                         else {
1695                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1696                                 return -1;
1697                         }
1698                 }
1699                 if (!res)
1700                         return 0;
1701                 p->cidpos += res;
1702         }
1703         free(p->cidspill);
1704         p->cidspill = NULL;
1705         if (p->callwaitcas) {
1706                 /* Wait for CID/CW to expire */
1707                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1708         } else
1709                 restore_conference(p);
1710         return 0;
1711 }
1712
1713 static int zt_callwait(struct ast_channel *ast)
1714 {
1715         struct zt_pvt *p = ast->tech_pvt;
1716         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1717         if (p->cidspill) {
1718                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1719                 free(p->cidspill);
1720         }
1721         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1722                 return -1;
1723         save_conference(p);
1724         /* Silence */
1725         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1726         if (!p->callwaitrings && p->callwaitingcallerid) {
1727                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1728                 p->callwaitcas = 1;
1729                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1730         } else {
1731                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1732                 p->callwaitcas = 0;
1733                 p->cidlen = 2400 + READ_SIZE * 4;
1734         }
1735         p->cidpos = 0;
1736         send_callerid(p);
1737         
1738         return 0;
1739 }
1740
1741 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1742 {
1743         struct zt_pvt *p = ast->tech_pvt;
1744         int x, res, index;
1745         char *c, *n, *l;
1746 #ifdef ZAPATA_PRI
1747         char *s=NULL;
1748 #endif
1749         char dest[256]; /* must be same length as p->dialdest */
1750         ast_mutex_lock(&p->lock);
1751         ast_copy_string(dest, rdest, sizeof(dest));
1752         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1753         if ((ast->_state == AST_STATE_BUSY)) {
1754                 p->subs[SUB_REAL].needbusy = 1;
1755                 ast_mutex_unlock(&p->lock);
1756                 return 0;
1757         }
1758         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1759                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1760                 ast_mutex_unlock(&p->lock);
1761                 return -1;
1762         }
1763         p->dialednone = 0;
1764         if (p->radio)  /* if a radio channel, up immediately */
1765         {
1766                 /* Special pseudo -- automatically up */
1767                 ast_setstate(ast, AST_STATE_UP); 
1768                 ast_mutex_unlock(&p->lock);
1769                 return 0;
1770         }
1771         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1772         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1773         if (res)
1774                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1775         p->outgoing = 1;
1776
1777         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1778
1779         switch(p->sig) {
1780         case SIG_FXOLS:
1781         case SIG_FXOGS:
1782         case SIG_FXOKS:
1783                 if (p->owner == ast) {
1784                         /* Normal ring, on hook */
1785                         
1786                         /* Don't send audio while on hook, until the call is answered */
1787                         p->dialing = 1;
1788                         if (p->use_callerid) {
1789                                 /* Generate the Caller-ID spill if desired */
1790                                 if (p->cidspill) {
1791                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1792                                         free(p->cidspill);
1793                                 }
1794                                 p->callwaitcas = 0;
1795                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1796                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1797                                         p->cidpos = 0;
1798                                         send_callerid(p);
1799                                 }
1800                         }
1801                         /* Choose proper cadence */
1802                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1803                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1804                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1805                                 p->cidrings = cidrings[p->distinctivering - 1];
1806                         } else {
1807                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1808                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1809                                 p->cidrings = p->sendcalleridafter;
1810                         }
1811
1812
1813                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1814                         c = strchr(dest, '/');
1815                         if (c)
1816                                 c++;
1817                         if (c && (strlen(c) < p->stripmsd)) {
1818                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1819                                 c = NULL;
1820                         }
1821                         if (c) {
1822                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1823                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1824                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1825                         } else {
1826                                 p->dop.dialstr[0] = '\0';
1827                         }
1828                         x = ZT_RING;
1829                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1830                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1831                                 ast_mutex_unlock(&p->lock);
1832                                 return -1;
1833                         }
1834                         p->dialing = 1;
1835                 } else {
1836                         /* Call waiting call */
1837                         p->callwaitrings = 0;
1838                         if (ast->cid.cid_num)
1839                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1840                         else
1841                                 p->callwait_num[0] = '\0';
1842                         if (ast->cid.cid_name)
1843                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1844                         else
1845                                 p->callwait_name[0] = '\0';
1846                         /* Call waiting tone instead */
1847                         if (zt_callwait(ast)) {
1848                                 ast_mutex_unlock(&p->lock);
1849                                 return -1;
1850                         }
1851                         /* Make ring-back */
1852                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1853                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1854                                 
1855                 }
1856                 n = ast->cid.cid_name;
1857                 l = ast->cid.cid_num;
1858                 if (l)
1859                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1860                 else
1861                         p->lastcid_num[0] = '\0';
1862                 if (n)
1863                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1864                 else
1865                         p->lastcid_name[0] = '\0';
1866                 ast_setstate(ast, AST_STATE_RINGING);
1867                 index = zt_get_index(ast, p, 0);
1868                 if (index > -1) {
1869                         p->subs[index].needringing = 1;
1870                 }
1871                 break;
1872         case SIG_FXSLS:
1873         case SIG_FXSGS:
1874         case SIG_FXSKS:
1875         case SIG_EMWINK:
1876         case SIG_EM:
1877         case SIG_EM_E1:
1878         case SIG_FEATD:
1879         case SIG_FEATDMF:
1880         case SIG_E911:
1881         case SIG_FGC_CAMA:
1882         case SIG_FGC_CAMAMF:
1883         case SIG_FEATB:
1884         case SIG_SFWINK:
1885         case SIG_SF:
1886         case SIG_SF_FEATD:
1887         case SIG_SF_FEATDMF:
1888         case SIG_FEATDMF_TA:
1889         case SIG_SF_FEATB:
1890                 c = strchr(dest, '/');
1891                 if (c)
1892                         c++;
1893                 else
1894                         c = "";
1895                 if (strlen(c) < p->stripmsd) {
1896                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1897                         ast_mutex_unlock(&p->lock);
1898                         return -1;
1899                 }
1900 #ifdef ZAPATA_PRI
1901                 /* Start the trunk, if not GR-303 */
1902                 if (!p->pri) {
1903 #endif
1904                         x = ZT_START;
1905                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1906                         if (res < 0) {
1907                                 if (errno != EINPROGRESS) {
1908                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1909                                         ast_mutex_unlock(&p->lock);
1910                                         return -1;
1911                                 }
1912                         }
1913 #ifdef ZAPATA_PRI
1914                 }
1915 #endif
1916                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1917                 p->dop.op = ZT_DIAL_OP_REPLACE;
1918
1919                 c += p->stripmsd;
1920
1921                 switch (p->sig) {
1922                 case SIG_FEATD:
1923                         l = ast->cid.cid_num;
1924                         if (l) 
1925                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
1926                         else
1927                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
1928                         break;
1929                 case SIG_FEATDMF:
1930                         l = ast->cid.cid_num;
1931                         if (l) 
1932                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
1933                         else
1934                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
1935                         break;
1936                 case SIG_FEATDMF_TA:
1937                 {
1938                         const char *cic, *ozz;
1939
1940                         /* If you have to go through a Tandem Access point you need to use this */
1941                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1942                         if (!ozz)
1943                                 ozz = defaultozz;
1944                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1945                         if (!cic)
1946                                 cic = defaultcic;
1947                         if (!ozz || !cic) {
1948                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1949                                 ast_mutex_unlock(&p->lock);
1950                                 return -1;
1951                         }
1952                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1953                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
1954                         p->whichwink = 0;
1955                 }
1956                         break;
1957                 case SIG_E911:
1958                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1959                         break;
1960                 case SIG_FGC_CAMA:
1961                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
1962                         break;
1963                 case SIG_FGC_CAMAMF:
1964                 case SIG_FEATB:
1965                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
1966                         break;
1967                 default:
1968                         if (p->pulse)
1969                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
1970                         else
1971                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
1972                         break;
1973                 }
1974
1975                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1976                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1977                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1978                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1979                         p->echobreak = 1;
1980                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1981                 } else
1982                         p->echobreak = 0;
1983                 if (!res) {
1984                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1985                                 x = ZT_ONHOOK;
1986                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1987                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1988                                 ast_mutex_unlock(&p->lock);
1989                                 return -1;
1990                         }
1991                 } else
1992                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1993                 p->dialing = 1;
1994                 if (ast_strlen_zero(c))
1995                         p->dialednone = 1;
1996                 ast_setstate(ast, AST_STATE_DIALING);
1997                 break;
1998         case 0:
1999                 /* Special pseudo -- automatically up*/
2000                 ast_setstate(ast, AST_STATE_UP);
2001                 break;          
2002         case SIG_PRI:
2003                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2004                 p->dialdest[0] = '\0';
2005                 break;
2006         default:
2007                 ast_log(LOG_DEBUG, "not yet implemented\n");
2008                 ast_mutex_unlock(&p->lock);
2009                 return -1;
2010         }
2011 #ifdef ZAPATA_PRI
2012         if (p->pri) {
2013                 struct pri_sr *sr;
2014                 const char *useruser;
2015                 int pridialplan;
2016                 int dp_strip;
2017                 int prilocaldialplan;
2018                 int ldp_strip;
2019                 int exclusive;
2020
2021                 c = strchr(dest, '/');
2022                 if (c)
2023                         c++;
2024                 else
2025                         c = dest;
2026                 if (!p->hidecallerid) {
2027                         l = ast->cid.cid_num;
2028                         n = ast->cid.cid_name;
2029                 } else {
2030                         l = NULL;
2031                         n = NULL;
2032                 }
2033                 if (strlen(c) < p->stripmsd) {
2034                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2035                         ast_mutex_unlock(&p->lock);
2036                         return -1;
2037                 }
2038                 if (p->sig != SIG_FXSKS) {
2039                         p->dop.op = ZT_DIAL_OP_REPLACE;
2040                         s = strchr(c + p->stripmsd, 'w');
2041                         if (s) {
2042                                 if (strlen(s) > 1)
2043                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2044                                 else
2045                                         p->dop.dialstr[0] = '\0';
2046                                 *s = '\0';
2047                         } else {
2048                                 p->dop.dialstr[0] = '\0';
2049                         }
2050                 }
2051                 if (pri_grab(p, p->pri)) {
2052                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2053                         ast_mutex_unlock(&p->lock);
2054                         return -1;
2055                 }
2056                 if (!(p->call = pri_new_call(p->pri->pri))) {
2057                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2058                         pri_rel(p->pri);
2059                         ast_mutex_unlock(&p->lock);
2060                         return -1;
2061                 }
2062                 if (!(sr = pri_sr_new())) {
2063                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2064                         pri_rel(p->pri);
2065                         ast_mutex_unlock(&p->lock);
2066                 }
2067                 if (p->bearer || (p->sig == SIG_FXSKS)) {
2068                         if (p->bearer) {
2069                                 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);
2070                                 p->bearer->call = p->call;
2071                         } else
2072                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2073                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2074                 }
2075                 p->digital = IS_DIGITAL(ast->transfercapability);
2076                 /* Add support for exclusive override */
2077                 if (p->priexclusive)
2078                         exclusive = 1;
2079                 else {
2080                 /* otherwise, traditional behavior */
2081                         if (p->pri->nodetype == PRI_NETWORK)
2082                                 exclusive = 0;
2083                         else
2084                                 exclusive = 1;
2085                 }
2086                 
2087                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2088                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2089                                         (p->digital ? -1 : 
2090                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2091                 if (p->pri->facilityenable)
2092                         pri_facility_enable(p->pri->pri);
2093
2094                 if (option_verbose > 2)
2095                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2096                 dp_strip = 0;
2097                 pridialplan = p->pri->dialplan - 1;
2098                 if (pridialplan == -2) { /* compute dynamically */
2099                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2100                                 dp_strip = strlen(p->pri->internationalprefix);
2101                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2102                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2103                                 dp_strip = strlen(p->pri->nationalprefix);
2104                                 pridialplan = PRI_NATIONAL_ISDN;
2105                         } else {
2106                                 pridialplan = PRI_LOCAL_ISDN;
2107                         }
2108                 }
2109                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  s ? 1 : 0);
2110
2111                 ldp_strip = 0;
2112                 prilocaldialplan = p->pri->localdialplan - 1;
2113                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
2114                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2115                                 ldp_strip = strlen(p->pri->internationalprefix);
2116                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2117                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2118                                 ldp_strip = strlen(p->pri->nationalprefix);
2119                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2120                         } else {
2121                                 prilocaldialplan = PRI_LOCAL_ISDN;
2122                         }
2123                 }
2124                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan, 
2125                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
2126                                                  PRES_NUMBER_NOT_AVAILABLE);
2127                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
2128                 /* User-user info */
2129                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2130
2131                 if (useruser)
2132                         pri_sr_set_useruser(sr, useruser);
2133
2134                 if (pri_setup(p->pri->pri, p->call,  sr)) {
2135                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2136                                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2137                         pri_rel(p->pri);
2138                         ast_mutex_unlock(&p->lock);
2139                         pri_sr_free(sr);
2140                         return -1;
2141                 }
2142                 pri_sr_free(sr);
2143                 ast_setstate(ast, AST_STATE_DIALING);
2144                 pri_rel(p->pri);
2145         }
2146 #endif          
2147         ast_mutex_unlock(&p->lock);
2148         return 0;
2149 }
2150
2151 static void destroy_zt_pvt(struct zt_pvt **pvt)
2152 {
2153         struct zt_pvt *p = *pvt;
2154         /* Remove channel from the list */
2155         if(p->prev)
2156                 p->prev->next = p->next;
2157         if(p->next)
2158                 p->next->prev = p->prev;
2159         ast_mutex_destroy(&p->lock);
2160         free(p);
2161         *pvt = NULL;
2162 }
2163
2164 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2165 {
2166         int owned = 0;
2167         int i = 0;
2168
2169         if (!now) {
2170                 if (cur->owner) {
2171                         owned = 1;
2172                 }
2173
2174                 for (i = 0; i < 3; i++) {
2175                         if (cur->subs[i].owner) {
2176                                 owned = 1;
2177                         }
2178                 }
2179                 if (!owned) {
2180                         if (prev) {
2181                                 prev->next = cur->next;
2182                                 if (prev->next)
2183                                         prev->next->prev = prev;
2184                                 else
2185                                         ifend = prev;
2186                         } else {
2187                                 iflist = cur->next;
2188                                 if (iflist)
2189                                         iflist->prev = NULL;
2190                                 else
2191                                         ifend = NULL;
2192                         }
2193                         if (cur->subs[SUB_REAL].zfd > -1) {
2194                                 zt_close(cur->subs[SUB_REAL].zfd);
2195                         }
2196                         destroy_zt_pvt(&cur);
2197                 }
2198         } else {
2199                 if (prev) {
2200                         prev->next = cur->next;
2201                         if (prev->next)
2202                                 prev->next->prev = prev;
2203                         else
2204                                 ifend = prev;
2205                 } else {
2206                         iflist = cur->next;
2207                         if (iflist)
2208                                 iflist->prev = NULL;
2209                         else
2210                                 ifend = NULL;
2211                 }
2212                 if (cur->subs[SUB_REAL].zfd > -1) {
2213                         zt_close(cur->subs[SUB_REAL].zfd);
2214                 }
2215                 destroy_zt_pvt(&cur);
2216         }
2217         return 0;
2218 }
2219
2220 #ifdef ZAPATA_PRI
2221 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2222
2223 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2224
2225 static char *zap_send_keypad_facility_descrip = 
2226 "  ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2227 "  IE over the current channel.\n";
2228
2229 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2230 {
2231         /* Data will be our digit string */
2232         struct zt_pvt *p;
2233         char *digits = (char *) data;
2234
2235         if (ast_strlen_zero(digits)) {
2236                 ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2237                 return -1;
2238         }
2239
2240         p = (struct zt_pvt *)chan->tech_pvt;
2241
2242         if (!p) {
2243                 ast_log(LOG_DEBUG, "Unable to find technology private\n");
2244                 return -1;
2245         }
2246
2247         ast_mutex_lock(&p->lock);
2248
2249         if (!p->pri || !p->call) {
2250                 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2251                 ast_mutex_unlock(&p->lock);
2252                 return -1;
2253         }
2254
2255         if (!pri_grab(p, p->pri)) {
2256                 pri_keypad_facility(p->pri->pri, p->call, digits);
2257                 pri_rel(p->pri);
2258         } else {
2259                 ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2260                 ast_mutex_unlock(&p->lock);
2261                 return -1;
2262         }
2263
2264         ast_mutex_unlock(&p->lock);
2265
2266         return 0;
2267 }
2268
2269 int pri_is_up(struct zt_pri *pri)
2270 {
2271         int x;
2272         for (x=0;x<NUM_DCHANS;x++) {
2273                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2274                         return 1;
2275         }
2276         return 0;
2277 }
2278
2279 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2280 {
2281         bearer->owner = &inuse;
2282         bearer->realcall = crv;
2283         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2284         if (crv->subs[SUB_REAL].owner)
2285                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2286         crv->bearer = bearer;
2287         crv->call = bearer->call;
2288         crv->pri = pri;
2289         return 0;
2290 }
2291
2292 static char *pri_order(int level)
2293 {
2294         switch(level) {
2295         case 0:
2296                 return "Primary";
2297         case 1:
2298                 return "Secondary";
2299         case 2:
2300                 return "Tertiary";
2301         case 3:
2302                 return "Quaternary";
2303         default:
2304                 return "<Unknown>";
2305         }               
2306 }
2307
2308 /* Returns fd of the active dchan */
2309 int pri_active_dchan_fd(struct zt_pri *pri)
2310 {
2311         int x = -1;
2312
2313         for (x = 0; x < NUM_DCHANS; x++) {
2314                 if ((pri->dchans[x] == pri->pri))
2315                         break;
2316         }
2317
2318         return pri->fds[x];
2319 }
2320
2321 int pri_find_dchan(struct zt_pri *pri)
2322 {
2323         int oldslot = -1;
2324         struct pri *old;
2325         int newslot = -1;
2326         int x;
2327         old = pri->pri;
2328         for(x=0;x<NUM_DCHANS;x++) {
2329                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2330                         newslot = x;
2331                 if (pri->dchans[x] == old) {
2332                         oldslot = x;
2333                 }
2334         }
2335         if (newslot < 0) {
2336                 newslot = 0;
2337                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2338                         pri->dchannels[newslot]);
2339         }
2340         if (old && (oldslot != newslot))
2341                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2342                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2343         pri->pri = pri->dchans[newslot];
2344         return 0;
2345 }
2346 #endif
2347
2348 static int zt_hangup(struct ast_channel *ast)
2349 {
2350         int res;
2351         int index,x, law;
2352         /*static int restore_gains(struct zt_pvt *p);*/
2353         struct zt_pvt *p = ast->tech_pvt;
2354         struct zt_pvt *tmp = NULL;
2355         struct zt_pvt *prev = NULL;
2356         ZT_PARAMS par;
2357
2358         if (option_debug)
2359                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2360         if (!ast->tech_pvt) {
2361                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2362                 return 0;
2363         }
2364         
2365         ast_mutex_lock(&p->lock);
2366         
2367         index = zt_get_index(ast, p, 1);
2368
2369         if (p->sig == SIG_PRI) {
2370                 x = 1;
2371                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2372         }
2373
2374         x = 0;
2375         zt_confmute(p, 0);
2376         restore_gains(p);
2377         if (p->origcid_num) {
2378                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2379                 free(p->origcid_num);
2380                 p->origcid_num = NULL;
2381         }       
2382         if (p->origcid_name) {
2383                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2384                 free(p->origcid_name);
2385                 p->origcid_name = NULL;
2386         }       
2387         if (p->dsp)
2388                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2389         if (p->exten)
2390                 p->exten[0] = '\0';
2391
2392         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2393                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2394         p->ignoredtmf = 0;
2395         
2396         if (index > -1) {
2397                 /* Real channel, do some fixup */
2398                 p->subs[index].owner = NULL;
2399                 p->subs[index].needanswer = 0;
2400                 p->subs[index].needflash = 0;
2401                 p->subs[index].needringing = 0;
2402                 p->subs[index].needbusy = 0;
2403                 p->subs[index].needcongestion = 0;
2404                 p->subs[index].linear = 0;
2405                 p->subs[index].needcallerid = 0;
2406                 p->polarity = POLARITY_IDLE;
2407                 zt_setlinear(p->subs[index].zfd, 0);
2408                 if (index == SUB_REAL) {
2409                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2410                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2411                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2412                                         /* We had flipped over to answer a callwait and now it's gone */
2413                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2414                                         /* Move to the call-wait, but un-own us until they flip back. */
2415                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2416                                         unalloc_sub(p, SUB_CALLWAIT);
2417                                         p->owner = NULL;
2418                                 } else {
2419                                         /* The three way hung up, but we still have a call wait */
2420                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2421                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2422                                         unalloc_sub(p, SUB_THREEWAY);
2423                                         if (p->subs[SUB_REAL].inthreeway) {
2424                                                 /* This was part of a three way call.  Immediately make way for
2425                                                    another call */
2426                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2427                                                 p->owner = p->subs[SUB_REAL].owner;
2428                                         } else {
2429                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2430                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2431                                                 p->owner = NULL;
2432                                         }
2433                                         p->subs[SUB_REAL].inthreeway = 0;
2434                                 }
2435                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2436                                 /* Move to the call-wait and switch back to them. */
2437                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2438                                 unalloc_sub(p, SUB_CALLWAIT);
2439                                 p->owner = p->subs[SUB_REAL].owner;
2440                                 if (p->owner->_state != AST_STATE_UP)
2441                                         p->subs[SUB_REAL].needanswer = 1;
2442                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2443                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2444                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2445                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2446                                 unalloc_sub(p, SUB_THREEWAY);
2447                                 if (p->subs[SUB_REAL].inthreeway) {
2448                                         /* This was part of a three way call.  Immediately make way for
2449                                            another call */
2450                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2451                                         p->owner = p->subs[SUB_REAL].owner;
2452                                 } else {
2453                                         /* This call hasn't been completed yet...  Set owner to NULL */
2454                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2455                                         p->owner = NULL;
2456                                 }
2457                                 p->subs[SUB_REAL].inthreeway = 0;
2458                         }
2459                 } else if (index == SUB_CALLWAIT) {
2460                         /* Ditch the holding callwait call, and immediately make it availabe */
2461                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2462                                 /* This is actually part of a three way, placed on hold.  Place the third part
2463                                    on music on hold now */
2464                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2465                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2466                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2467                                 /* Make it the call wait now */
2468                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2469                                 unalloc_sub(p, SUB_THREEWAY);
2470                         } else
2471                                 unalloc_sub(p, SUB_CALLWAIT);
2472                 } else if (index == SUB_THREEWAY) {
2473                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2474                                 /* The other party of the three way call is currently in a call-wait state.
2475                                    Start music on hold for them, and take the main guy out of the third call */
2476                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2477                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2478                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2479                         }
2480                         p->subs[SUB_REAL].inthreeway = 0;
2481                         /* If this was part of a three way call index, let us make
2482                            another three way call */
2483                         unalloc_sub(p, SUB_THREEWAY);
2484                 } else {
2485                         /* This wasn't any sort of call, but how are we an index? */
2486                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2487                 }
2488         }
2489
2490
2491         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2492                 p->owner = NULL;
2493                 p->ringt = 0;
2494                 p->distinctivering = 0;
2495                 p->confirmanswer = 0;
2496                 p->cidrings = 1;
2497                 p->outgoing = 0;
2498                 p->digital = 0;
2499                 p->faxhandled = 0;
2500                 p->pulsedial = 0;
2501                 p->onhooktime = time(NULL);
2502 #ifdef ZAPATA_PRI
2503                 p->proceeding = 0;
2504                 p->progress = 0;
2505                 p->alerting = 0;
2506                 p->setup_ack = 0;
2507 #endif          
2508                 if (p->dsp) {
2509                         ast_dsp_free(p->dsp);
2510                         p->dsp = NULL;
2511                 }
2512
2513                 law = ZT_LAW_DEFAULT;
2514                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2515                 if (res < 0) 
2516                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2517                 /* Perform low level hangup if no owner left */
2518 #ifdef ZAPATA_PRI
2519                 if (p->pri) {
2520                         const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2521                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2522                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2523                                 if (!pri_grab(p, p->pri)) {
2524                                         if (p->alreadyhungup) {
2525                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2526                                                 pri_call_set_useruser(p->call, useruser);
2527                                                 pri_hangup(p->pri->pri, p->call, -1);
2528                                                 p->call = NULL;
2529                                                 if (p->bearer) 
2530                                                         p->bearer->call = NULL;
2531                                         } else {
2532                                                 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2533                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2534                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2535                                                 pri_call_set_useruser(p->call, useruser);
2536                                                 p->alreadyhungup = 1;
2537                                                 if (p->bearer)
2538                                                         p->bearer->alreadyhungup = 1;
2539                                                 if (cause) {
2540                                                         if (atoi(cause))
2541                                                                 icause = atoi(cause);
2542                                                 }
2543                                                 pri_hangup(p->pri->pri, p->call, icause);
2544                                         }
2545                                         if (res < 0) 
2546                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2547                                         pri_rel(p->pri);                        
2548                                 } else {
2549                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2550                                         res = -1;
2551                                 }
2552                         } else {
2553                                 if (p->bearer)
2554                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2555                                 p->call = NULL;
2556                                 res = 0;
2557                         }
2558                 }
2559 #endif
2560 #ifdef ZAPATA_R2
2561                 if (p->sig == SIG_R2) {
2562                         if (p->hasr2call) {
2563                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2564                                 p->hasr2call = 0;
2565                                 res = 0;
2566                         } else
2567                                 res = 0;
2568
2569                 }
2570 #endif
2571                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2572                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2573                 if (res < 0) {
2574                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2575                 }
2576                 switch(p->sig) {
2577                 case SIG_FXOGS:
2578                 case SIG_FXOLS:
2579                 case SIG_FXOKS:
2580                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2581                         if (!res) {
2582 #if 0
2583                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2584 #endif
2585                                 /* If they're off hook, try playing congestion */
2586                                 if ((par.rxisoffhook) && (!p->radio))
2587                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2588                                 else
2589                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2590                         }
2591                         break;
2592                 case SIG_FXSGS:
2593                 case SIG_FXSLS:
2594                 case SIG_FXSKS:
2595                         /* Make sure we're not made available for at least two seconds assuming
2596                            we were actually used for an inbound or outbound call. */
2597                         if (ast->_state != AST_STATE_RESERVED) {
2598                                 time(&p->guardtime);
2599                                 p->guardtime += 2;
2600                         }
2601                         break;
2602                 default:
2603                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2604                 }
2605                 if (p->cidspill)
2606                         free(p->cidspill);
2607                 if (p->sig)
2608                         zt_disable_ec(p);
2609                 x = 0;
2610                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2611                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2612                 p->didtdd = 0;
2613                 p->cidspill = NULL;
2614                 p->callwaitcas = 0;
2615                 p->callwaiting = p->permcallwaiting;
2616                 p->hidecallerid = p->permhidecallerid;
2617                 p->dialing = 0;
2618                 p->rdnis[0] = '\0';
2619                 update_conf(p);
2620                 reset_conf(p);
2621                 /* Restore data mode */
2622                 if (p->sig == SIG_PRI) {
2623                         x = 0;
2624                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2625                 }
2626 #ifdef ZAPATA_PRI
2627                 if (p->bearer) {
2628                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2629                         /* Free up the bearer channel as well, and
2630                            don't use its file descriptor anymore */
2631                         update_conf(p->bearer);
2632                         reset_conf(p->bearer);
2633                         p->bearer->owner = NULL;
2634                         p->bearer->realcall = NULL;
2635                         p->bearer = NULL;
2636                         p->subs[SUB_REAL].zfd = -1;
2637                         p->pri = NULL;
2638                 }
2639 #endif
2640                 restart_monitor();
2641         }
2642
2643
2644         p->callwaitingrepeat = 0;
2645         p->cidcwexpire = 0;
2646         ast->tech_pvt = NULL;
2647         ast_mutex_unlock(&p->lock);
2648         ast_mutex_lock(&usecnt_lock);
2649         usecnt--;
2650         if (usecnt < 0) 
2651                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2652         ast_mutex_unlock(&usecnt_lock);
2653         ast_update_use_count();
2654         if (option_verbose > 2) 
2655                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2656
2657         ast_mutex_lock(&iflock);
2658         tmp = iflist;
2659         prev = NULL;
2660         if (p->destroy) {
2661                 while (tmp) {
2662                         if (tmp == p) {
2663                                 destroy_channel(prev, tmp, 0);
2664                                 break;
2665                         } else {
2666                                 prev = tmp;
2667                                 tmp = tmp->next;
2668                         }
2669                 }
2670         }
2671         ast_mutex_unlock(&iflock);
2672         return 0;
2673 }
2674
2675 static int zt_answer(struct ast_channel *ast)
2676 {
2677         struct zt_pvt *p = ast->tech_pvt;
2678         int res=0;
2679         int index;
2680         int oldstate = ast->_state;
2681         ast_setstate(ast, AST_STATE_UP);
2682         ast_mutex_lock(&p->lock);
2683         index = zt_get_index(ast, p, 0);
2684         if (index < 0)
2685                 index = SUB_REAL;
2686         /* nothing to do if a radio channel */
2687         if (p->radio) {
2688                 ast_mutex_unlock(&p->lock);
2689                 return 0;
2690         }
2691         switch(p->sig) {
2692         case SIG_FXSLS:
2693         case SIG_FXSGS:
2694         case SIG_FXSKS:
2695                 p->ringt = 0;
2696                 /* Fall through */
2697         case SIG_EM:
2698         case SIG_EM_E1:
2699         case SIG_EMWINK:
2700         case SIG_FEATD:
2701         case SIG_FEATDMF:
2702         case SIG_FEATDMF_TA:
2703         case SIG_E911:
2704         case SIG_FGC_CAMA:
2705         case SIG_FGC_CAMAMF:
2706         case SIG_FEATB:
2707         case SIG_SF:
2708         case SIG_SFWINK:
2709         case SIG_SF_FEATD:
2710         case SIG_SF_FEATDMF:
2711         case SIG_SF_FEATB:
2712         case SIG_FXOLS:
2713         case SIG_FXOGS:
2714         case SIG_FXOKS:
2715                 /* Pick up the line */
2716                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2717                 if(p->hanguponpolarityswitch) {
2718                         gettimeofday(&p->polaritydelaytv, NULL);
2719                 }
2720                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2721                 tone_zone_play_tone(p->subs[index].zfd, -1);
2722                 p->dialing = 0;
2723                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2724                         if (oldstate == AST_STATE_RINGING) {
2725                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2726                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2727                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2728                                 p->owner = p->subs[SUB_REAL].owner;
2729                         }
2730                 }
2731                 if (p->sig & __ZT_SIG_FXS) {
2732                         zt_enable_ec(p);
2733                         zt_train_ec(p);
2734                 }
2735                 break;
2736 #ifdef ZAPATA_PRI
2737         case SIG_PRI:
2738                 /* Send a pri acknowledge */
2739                 if (!pri_grab(p, p->pri)) {
2740                         p->proceeding = 1;
2741                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2742                         pri_rel(p->pri);
2743                 } else {
2744                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2745                         res= -1;
2746                 }
2747                 break;
2748 #endif
2749 #ifdef ZAPATA_R2
2750         case SIG_R2:
2751                 res = mfcr2_AnswerCall(p->r2, NULL);
2752                 if (res)
2753                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2754                 break;
2755 #endif                  
2756         case 0:
2757                 ast_mutex_unlock(&p->lock);
2758                 return 0;
2759         default:
2760                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2761                 res = -1;
2762         }
2763         ast_mutex_unlock(&p->lock);
2764         return res;
2765 }
2766
2767 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2768 {
2769         char *cp;
2770         signed char *scp;
2771         int x;
2772         int index;
2773         struct zt_pvt *p = chan->tech_pvt;
2774
2775         /* all supported options require data */
2776         if (!data || (datalen < 1)) {
2777                 errno = EINVAL;
2778                 return -1;
2779         }
2780
2781         switch(option) {
2782         case AST_OPTION_TXGAIN:
2783                 scp = (signed char *) data;
2784                 index = zt_get_index(chan, p, 0);
2785                 if (index < 0) {
2786                         ast_log(LOG_WARNING, "No index in TXGAIN?\n");
2787                         return -1;
2788                 }
2789                 ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
2790                 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
2791         case AST_OPTION_RXGAIN:
2792                 scp = (signed char *) data;
2793                 index = zt_get_index(chan, p, 0);
2794                 if (index < 0) {
2795                         ast_log(LOG_WARNING, "No index in RXGAIN?\n");
2796                         return -1;
2797                 }
2798                 ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
2799                 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
2800         case AST_OPTION_TONE_VERIFY:
2801                 if (!p->dsp)
2802                         break;
2803                 cp = (char *) data;
2804                 switch (*cp) {
2805                 case 1:
2806                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2807                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2808                         break;
2809                 case 2:
2810                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2811                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2812                         break;
2813                 default:
2814                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2815                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2816                         break;
2817                 }
2818                 break;
2819         case AST_OPTION_TDD:
2820                 /* turn on or off TDD */
2821                 cp = (char *) data;
2822                 p->mate = 0;
2823                 if (!*cp) { /* turn it off */
2824                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2825                         if (p->tdd) tdd_free(p->tdd);
2826                         p->tdd = 0;
2827                         break;
2828                 }
2829                 ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
2830                         (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
2831                 zt_disable_ec(p);
2832                 /* otherwise, turn it on */
2833                 if (!p->didtdd) { /* if havent done it yet */
2834                         unsigned char mybuf[41000],*buf;
2835                         int size,res,fd,len;
2836                         struct pollfd fds[1];
2837
2838                         buf = mybuf;
2839                         memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
2840                         ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
2841                         len = 40000;
2842                         index = zt_get_index(chan, p, 0);
2843                         if (index < 0) {
2844                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2845                                 return -1;
2846                         }
2847                         fd = p->subs[index].zfd;
2848                         while(len) {
2849                                 if (ast_check_hangup(chan)) return -1;
2850                                 size = len;
2851                                 if (size > READ_SIZE)
2852                                         size = READ_SIZE;
2853                                 fds[0].fd = fd;
2854                                 fds[0].events = POLLPRI | POLLOUT;
2855                                 fds[0].revents = 0;
2856                                 res = poll(fds, 1, -1);
2857                                 if (!res) {
2858                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2859                                         continue;
2860                                 }
2861                                 /* if got exception */
2862                                 if (fds[0].revents & POLLPRI) return -1;
2863                                 if (!(fds[0].revents & POLLOUT)) {
2864                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2865                                         continue;
2866                                 }
2867                                 res = write(fd, buf, size);
2868                                 if (res != size) {
2869                                         if (res == -1) return -1;
2870                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2871                                         break;
2872                                 }
2873                                 len -= size;
2874                                 buf += size;
2875                         }
2876                         p->didtdd = 1; /* set to have done it now */            
2877                 }
2878                 if (*cp == 2) { /* Mate mode */
2879                         if (p->tdd) tdd_free(p->tdd);
2880                         p->tdd = 0;
2881                         p->mate = 1;
2882                         break;
2883                 }               
2884                 if (!p->tdd) { /* if we dont have one yet */
2885                         p->tdd = tdd_new(); /* allocate one */
2886                 }               
2887                 break;
2888         case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2889                 if (!p->dsp)
2890                         break;
2891                 cp = (char *) data;
2892                 ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
2893                         *cp ? "ON" : "OFF", (int) *cp, chan->name);
2894                 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
2895                 break;
2896         case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2897                 cp = (char *) data;
2898                 if (!*cp) {             
2899                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
2900                         x = 0;
2901                         zt_disable_ec(p);
2902                 } else {                
2903                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
2904                         x = 1;
2905                 }
2906                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2907                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2908                 break;
2909         }
2910         errno = 0;
2911
2912         return 0;
2913 }
2914
2915 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2916 {
2917         /* Unlink a specific slave or all slaves/masters from a given master */
2918         int x;
2919         int hasslaves;
2920         if (!master)
2921                 return;
2922         if (needlock) {
2923                 ast_mutex_lock(&master->lock);
2924                 if (slave) {
2925                         while(ast_mutex_trylock(&slave->lock)) {
2926                                 ast_mutex_unlock(&master->lock);
2927                                 usleep(1);
2928                                 ast_mutex_lock(&master->lock);
2929                         }
2930                 }
2931         }
2932         hasslaves = 0;
2933         for (x=0;x<MAX_SLAVES;x++) {
2934                 if (master->slaves[x]) {
2935                         if (!slave || (master->slaves[x] == slave)) {
2936                                 /* Take slave out of the conference */
2937                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2938                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2939                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2940                                 master->slaves[x]->master = NULL;
2941                                 master->slaves[x] = NULL;
2942                         } else
2943                                 hasslaves = 1;
2944                 }
2945                 if (!hasslaves)
2946                         master->inconference = 0;
2947         }
2948         if (!slave) {
2949                 if (master->master) {
2950                         /* Take master out of the conference */
2951                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2952                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2953                         hasslaves = 0;
2954                         for (x=0;x<MAX_SLAVES;x++) {
2955                                 if (master->master->slaves[x] == master)
2956                                         master->master->slaves[x] = NULL;
2957                                 else if (master->master->slaves[x])
2958                                         hasslaves = 1;
2959                         }
2960                         if (!hasslaves)
2961                                 master->master->inconference = 0;
2962                 }
2963                 master->master = NULL;
2964         }
2965         update_conf(master);
2966         if (needlock) {
2967                 if (slave)
2968                         ast_mutex_unlock(&slave->lock);
2969                 ast_mutex_unlock(&master->lock);
2970         }
2971 }
2972
2973 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2974         int x;
2975         if (!slave || !master) {
2976                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2977                 return;
2978         }
2979         for (x=0;x<MAX_SLAVES;x++) {
2980                 if (!master->slaves[x]) {
2981                         master->slaves[x] = slave;
2982                         break;
2983                 }
2984         }
2985         if (x >= MAX_SLAVES) {
2986                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2987                 master->slaves[MAX_SLAVES - 1] = slave;
2988         }
2989         if (slave->master) 
2990                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2991         slave->master = master;
2992         
2993         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2994 }
2995
2996 static void disable_dtmf_detect(struct zt_pvt *p)
2997 {
2998 #ifdef ZT_TONEDETECT
2999         int val;
3000 #endif
3001
3002         p->ignoredtmf = 1;
3003
3004 #ifdef ZT_TONEDETECT
3005         val = 0;
3006         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3007 #endif          
3008         if (!p->hardwaredtmf && p->dsp) {
3009                 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3010                 ast_dsp_set_features(p->dsp, p->dsp_features);
3011         }
3012 }
3013
3014 static void enable_dtmf_detect(struct zt_pvt *p)
3015 {
3016 #ifdef ZT_TONEDETECT
3017         int val;
3018 #endif
3019
3020         if (p->channel == CHAN_PSEUDO)
3021                 return;
3022
3023         p->ignoredtmf = 0;
3024
3025 #ifdef ZT_TONEDETECT
3026         val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3027         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3028 #endif          
3029         if (!p->hardwaredtmf && p->dsp) {
3030                 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3031                 ast_dsp_set_features(p->dsp, p->dsp_features);
3032         }
3033 }
3034
3035 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)
3036 {
3037         struct ast_channel *who;
3038         struct zt_pvt *p0, *p1, *op0, *op1;