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