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