1fe7c95f31d88427b925fbfffa7b5c2d34618ba5
[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         char orig_called_num[50];
688         unsigned char gen_add_num_plan;
689         unsigned char gen_add_nai;
690         unsigned char gen_add_pres_ind;
691         unsigned char gen_add_type;
692         unsigned char gen_dig_type;
693         unsigned char gen_dig_scheme;
694         char jip_number[50];
695         unsigned char lspi_type;
696         unsigned char lspi_scheme;
697         unsigned char lspi_context;
698         char lspi_ident[50];
699         unsigned int call_ref_ident;
700         unsigned int call_ref_pc;
701         int transcap;
702         int cic;                                                        /*!< CIC associated with channel */
703         unsigned int dpc;                                               /*!< CIC's DPC */
704         unsigned int loopedback:1;
705 #endif
706         char begindigit;
707 } *iflist = NULL, *ifend = NULL;
708
709 /*! \brief Channel configuration from zapata.conf .
710  * This struct is used for parsing the [channels] section of zapata.conf.
711  * Generally there is a field here for every possible configuration item.
712  *
713  * The state of fields is saved along the parsing and whenever a 'channel'
714  * statement is reached, the current zt_chan_conf is used to configure the 
715  * channel (struct zt_pvt)
716  *
717  * \see zt_chan_init for the default values.
718  */
719 struct zt_chan_conf {
720         struct zt_pvt chan;
721 #ifdef HAVE_PRI
722         struct zt_pri pri;
723 #endif
724
725 #ifdef HAVE_SS7
726         struct zt_ss7 ss7;
727 #endif
728         ZT_PARAMS timing;
729         int is_sig_auto; /*!< Use channel signalling from Zaptel? */
730
731         char smdi_port[SMDI_MAX_FILENAME_LEN];
732 };
733
734 /*! returns a new zt_chan_conf with default values (by-value) */
735 static struct zt_chan_conf zt_chan_conf_default(void) {
736         /* recall that if a field is not included here it is initialized
737          * to 0 or equivalent
738          */
739         struct zt_chan_conf conf = {
740 #ifdef HAVE_PRI
741                 .pri = {
742                         .nsf = PRI_NSF_NONE,
743                         .switchtype = PRI_SWITCH_NI2,
744                         .dialplan = PRI_NATIONAL_ISDN + 1,
745                         .localdialplan = PRI_NATIONAL_ISDN + 1,
746                         .nodetype = PRI_CPE,
747
748                         .minunused = 2,
749                         .idleext = "",
750                         .idledial = "",
751                         .internationalprefix = "",
752                         .nationalprefix = "",
753                         .localprefix = "",
754                         .privateprefix = "",
755                         .unknownprefix = "",
756                         .resetinterval = -1,
757                 },
758 #endif
759 #ifdef HAVE_SS7
760                 .ss7 = {
761                         .called_nai = SS7_NAI_NATIONAL,
762                         .calling_nai = SS7_NAI_NATIONAL,
763                         .internationalprefix = "",
764                         .nationalprefix = "",
765                         .subscriberprefix = "",
766                         .unknownprefix = ""
767                 },
768 #endif
769                 .chan = {
770                         .context = "default",
771                         .cid_num = "",
772                         .cid_name = "",
773                         .mohinterpret = "default",
774                         .mohsuggest = "",
775                         .transfertobusy = 1,
776
777                         .cid_signalling = CID_SIG_BELL,
778                         .cid_start = CID_START_RING,
779                         .zaptrcallerid = 0,
780                         .use_callerid = 1,
781                         .sig = -1,
782                         .outsigmod = -1,
783
784                         .cid_rxgain = +5.0,
785
786                         .tonezone = -1,
787
788 #if defined(HAVE_ZAPTEL_ECHOCANPARAMS)
789                         .echocancel.head.tap_length = 1,
790 #else
791                         .echocancel = 1,
792 #endif
793
794                         .busycount = 3,
795
796                         .accountcode = "",
797
798                         .mailbox = "",
799
800
801                         .polarityonanswerdelay = 600,
802
803                         .sendcalleridafter = DEFAULT_CIDRINGS
804                 },
805                 .timing = {
806                         .prewinktime = -1,
807                         .preflashtime = -1,
808                         .winktime = -1,
809                         .flashtime = -1,
810                         .starttime = -1,
811                         .rxwinktime = -1,
812                         .rxflashtime = -1,
813                         .debouncetime = -1
814                 },
815                 .is_sig_auto = 1,
816                 .smdi_port = "/dev/ttyS0",
817         };
818
819         return conf;
820 }
821
822
823 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
824 static int zt_digit_begin(struct ast_channel *ast, char digit);
825 static int zt_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
826 static int zt_sendtext(struct ast_channel *c, const char *text);
827 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
828 static int zt_hangup(struct ast_channel *ast);
829 static int zt_answer(struct ast_channel *ast);
830 static struct ast_frame *zt_read(struct ast_channel *ast);
831 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
832 static struct ast_frame *zt_exception(struct ast_channel *ast);
833 static int zt_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
834 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
835 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
836 static int zt_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
837
838 static const struct ast_channel_tech zap_tech = {
839         .type = "Zap",
840         .description = tdesc,
841         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
842         .requester = zt_request,
843         .send_digit_begin = zt_digit_begin,
844         .send_digit_end = zt_digit_end,
845         .send_text = zt_sendtext,
846         .call = zt_call,
847         .hangup = zt_hangup,
848         .answer = zt_answer,
849         .read = zt_read,
850         .write = zt_write,
851         .bridge = zt_bridge,
852         .exception = zt_exception,
853         .indicate = zt_indicate,
854         .fixup = zt_fixup,
855         .setoption = zt_setoption,
856         .func_channel_read = zt_func_read,
857 };
858
859 #ifdef HAVE_PRI
860 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
861 #else
862 #define GET_CHANNEL(p) ((p)->channel)
863 #endif
864
865 struct zt_pvt *round_robin[32];
866
867 #ifdef HAVE_PRI
868 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
869 {
870         int res;
871         /* Grab the lock first */
872         do {
873                 res = ast_mutex_trylock(&pri->lock);
874                 if (res) {
875                         ast_mutex_unlock(&pvt->lock);
876                         /* Release the lock and try again */
877                         usleep(1);
878                         ast_mutex_lock(&pvt->lock);
879                 }
880         } while (res);
881         /* Then break the poll */
882         pthread_kill(pri->master, SIGURG);
883         return 0;
884 }
885 #endif
886
887 #ifdef HAVE_SS7
888 static inline void ss7_rel(struct zt_ss7 *ss7)
889 {
890         ast_mutex_unlock(&ss7->lock);
891 }
892
893 static inline int ss7_grab(struct zt_pvt *pvt, struct zt_ss7 *pri)
894 {
895         int res;
896         /* Grab the lock first */
897         do {
898                 res = ast_mutex_trylock(&pri->lock);
899                 if (res) {
900                         ast_mutex_unlock(&pvt->lock);
901                         /* Release the lock and try again */
902                         usleep(1);
903                         ast_mutex_lock(&pvt->lock);
904                 }
905         } while (res);
906         /* Then break the poll */
907         pthread_kill(pri->master, SIGURG);
908         return 0;
909 }
910 #endif
911 #define NUM_CADENCE_MAX 25
912 static int num_cadence = 4;
913 static int user_has_defined_cadences = 0;
914
915 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
916         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
917         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
918         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
919         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
920 };
921
922 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
923  * is 1, the second pause is 2 and so on.
924  */
925
926 static int cidrings[NUM_CADENCE_MAX] = {
927         2,                                                                              /*!< Right after first long ring */
928         4,                                                                              /*!< Right after long part */
929         3,                                                                              /*!< After third chirp */
930         2,                                                                              /*!< Second spell */
931 };
932
933 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
934                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
935
936 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
937 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
938
939 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
940 {
941         int res;
942         if (p->subs[0].owner == ast)
943                 res = 0;
944         else if (p->subs[1].owner == ast)
945                 res = 1;
946         else if (p->subs[2].owner == ast)
947                 res = 2;
948         else {
949                 res = -1;
950                 if (!nullok)
951                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
952         }
953         return res;
954 }
955
956 #ifdef HAVE_PRI
957 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
958 #else
959 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
960 #endif
961 {
962 #ifdef HAVE_PRI
963         if (pri)
964                 ast_mutex_unlock(&pri->lock);
965 #endif                  
966         for (;;) {
967                 if (p->subs[a].owner) {
968                         if (ast_channel_trylock(p->subs[a].owner)) {
969                                 ast_mutex_unlock(&p->lock);
970                                 usleep(1);
971                                 ast_mutex_lock(&p->lock);
972                         } else {
973                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
974                                 ast_channel_unlock(p->subs[a].owner);
975                                 break;
976                         }
977                 } else
978                         break;
979         }
980 #ifdef HAVE_PRI
981         if (pri)
982                 ast_mutex_lock(&pri->lock);
983 #endif                  
984 }
985
986 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *data)
987 {
988 #ifdef HAVE_PRI
989         struct zt_pri *pri = (struct zt_pri*) data;
990 #endif
991 #ifdef HAVE_SS7
992         struct zt_ss7 *ss7 = (struct zt_ss7*) data;
993 #endif
994         /* We must unlock the PRI to avoid the possibility of a deadlock */
995 #if defined(HAVE_PRI) || defined(HAVE_SS7)
996         if (data) {
997                 switch (p->sig) {
998 #ifdef HAVE_PRI
999                 case SIG_BRI:
1000                 case SIG_BRI_PTMP:
1001                 case SIG_PRI:
1002                         ast_mutex_unlock(&pri->lock);
1003                         break;
1004 #endif
1005 #ifdef HAVE_SS7
1006                 case SIG_SS7:
1007                         ast_mutex_unlock(&ss7->lock);
1008                         break;
1009 #endif
1010                 default:
1011                         break;
1012                 }
1013         }
1014 #endif          
1015         for (;;) {
1016                 if (p->owner) {
1017                         if (ast_channel_trylock(p->owner)) {
1018                                 ast_mutex_unlock(&p->lock);
1019                                 usleep(1);
1020                                 ast_mutex_lock(&p->lock);
1021                         } else {
1022                                 ast_queue_frame(p->owner, f);
1023                                 ast_channel_unlock(p->owner);
1024                                 break;
1025                         }
1026                 } else
1027                         break;
1028         }
1029 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1030         if (data) {
1031                 switch (p->sig) {
1032 #ifdef HAVE_PRI
1033                 case SIG_BRI:
1034                 case SIG_BRI_PTMP:
1035                 case SIG_PRI:
1036                         ast_mutex_lock(&pri->lock);
1037                         break;
1038 #endif
1039 #ifdef HAVE_SS7
1040                 case SIG_SS7:
1041                         ast_mutex_lock(&ss7->lock);
1042                         break;
1043 #endif
1044                 default:
1045                         break;
1046                 }
1047         }
1048
1049 #endif          
1050 }
1051
1052 static int restore_gains(struct zt_pvt *p);
1053
1054 static void swap_subs(struct zt_pvt *p, int a, int b)
1055 {
1056         int tchan;
1057         int tinthreeway;
1058         struct ast_channel *towner;
1059
1060         ast_debug(1, "Swapping %d and %d\n", a, b);
1061
1062         tchan = p->subs[a].chan;
1063         towner = p->subs[a].owner;
1064         tinthreeway = p->subs[a].inthreeway;
1065
1066         p->subs[a].chan = p->subs[b].chan;
1067         p->subs[a].owner = p->subs[b].owner;
1068         p->subs[a].inthreeway = p->subs[b].inthreeway;
1069
1070         p->subs[b].chan = tchan;
1071         p->subs[b].owner = towner;
1072         p->subs[b].inthreeway = tinthreeway;
1073
1074         if (p->subs[a].owner) 
1075                 ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].zfd);
1076         if (p->subs[b].owner) 
1077                 ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].zfd);
1078         wakeup_sub(p, a, NULL);
1079         wakeup_sub(p, b, NULL);
1080 }
1081
1082 static int zt_open(char *fn)
1083 {
1084         int fd;
1085         int isnum;
1086         int chan = 0;
1087         int bs;
1088         int x;
1089         isnum = 1;
1090         for (x = 0; x < strlen(fn); x++) {
1091                 if (!isdigit(fn[x])) {
1092                         isnum = 0;
1093                         break;
1094                 }
1095         }
1096         if (isnum) {
1097                 chan = atoi(fn);
1098                 if (chan < 1) {
1099                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
1100                         return -1;
1101                 }
1102                 fn = "/dev/zap/channel";
1103         }
1104         fd = open(fn, O_RDWR | O_NONBLOCK);
1105         if (fd < 0) {
1106                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
1107                 return -1;
1108         }
1109         if (chan) {
1110                 if (ioctl(fd, ZT_SPECIFY, &chan)) {
1111                         x = errno;
1112                         close(fd);
1113                         errno = x;
1114                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
1115                         return -1;
1116                 }
1117         }
1118         bs = READ_SIZE;
1119         if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) {
1120                 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
1121                 x = errno;
1122                 close(fd);
1123                 errno = x;
1124                 return -1;
1125         }
1126         return fd;
1127 }
1128
1129 static void zt_close(int fd)
1130 {
1131         if (fd > 0)
1132                 close(fd);
1133 }
1134
1135 static int zt_setlinear(int zfd, int linear)
1136 {
1137         int res;
1138         res = ioctl(zfd, ZT_SETLINEAR, &linear);
1139         if (res)
1140                 return res;
1141         return 0;
1142 }
1143
1144
1145 static int alloc_sub(struct zt_pvt *p, int x)
1146 {
1147         ZT_BUFFERINFO bi;
1148         int res;
1149         if (p->subs[x].zfd < 0) {
1150                 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
1151                 if (p->subs[x].zfd > -1) {
1152                         res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
1153                         if (!res) {
1154                                 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
1155                                 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
1156                                 bi.numbufs = numbufs;
1157                                 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
1158                                 if (res < 0) {
1159                                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
1160                                 }
1161                         } else 
1162                                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
1163                         if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
1164                                 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
1165                                 zt_close(p->subs[x].zfd);
1166                                 p->subs[x].zfd = -1;
1167                                 return -1;
1168                         }
1169                         ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
1170                         return 0;
1171                 } else
1172                         ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
1173                 return -1;
1174         }
1175         ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
1176         return -1;
1177 }
1178
1179 static int unalloc_sub(struct zt_pvt *p, int x)
1180 {
1181         if (!x) {
1182                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
1183                 return -1;
1184         }
1185         ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
1186         if (p->subs[x].zfd > -1) {
1187                 zt_close(p->subs[x].zfd);
1188         }
1189         p->subs[x].zfd = -1;
1190         p->subs[x].linear = 0;
1191         p->subs[x].chan = 0;
1192         p->subs[x].owner = NULL;
1193         p->subs[x].inthreeway = 0;
1194         p->polarity = POLARITY_IDLE;
1195         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
1196         return 0;
1197 }
1198
1199 static int digit_to_dtmfindex(char digit)
1200 {
1201         if (isdigit(digit))
1202                 return ZT_TONE_DTMF_BASE + (digit - '0');
1203         else if (digit >= 'A' && digit <= 'D')
1204                 return ZT_TONE_DTMF_A + (digit - 'A');
1205         else if (digit >= 'a' && digit <= 'd')
1206                 return ZT_TONE_DTMF_A + (digit - 'a');
1207         else if (digit == '*')
1208                 return ZT_TONE_DTMF_s;
1209         else if (digit == '#')
1210                 return ZT_TONE_DTMF_p;
1211         else
1212                 return -1;
1213 }
1214
1215 static int zt_digit_begin(struct ast_channel *chan, char digit)
1216 {
1217         struct zt_pvt *pvt;
1218         int index;
1219         int dtmf = -1;
1220         
1221         pvt = chan->tech_pvt;
1222
1223         ast_mutex_lock(&pvt->lock);
1224
1225         index = zt_get_index(chan, pvt, 0);
1226
1227         if ((index != SUB_REAL) || !pvt->owner)
1228                 goto out;
1229
1230 #ifdef HAVE_PRI
1231         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP)) 
1232                         && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1233                 if (pvt->setup_ack) {
1234                         if (!pri_grab(pvt, pvt->pri)) {
1235                                 pri_information(pvt->pri->pri, pvt->call, digit);
1236                                 pri_rel(pvt->pri);
1237                         } else
1238                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1239                 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1240                         int res;
1241                         ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1242                         res = strlen(pvt->dialdest);
1243                         pvt->dialdest[res++] = digit;
1244                         pvt->dialdest[res] = '\0';
1245                 }
1246                 goto out;
1247         }
1248 #endif
1249         if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1250                 goto out;
1251
1252         if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &dtmf)) {
1253                 int res;
1254                 ZT_DIAL_OPERATION zo = {
1255                         .op = ZT_DIAL_OP_APPEND,
1256                 };
1257
1258                 zo.dialstr[0] = 'T';
1259                 zo.dialstr[1] = digit;
1260                 zo.dialstr[2] = '\0';
1261                 if ((res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
1262                         ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1263                 else
1264                         pvt->dialing = 1;
1265         } else {
1266                 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
1267                 pvt->dialing = 1;
1268                 pvt->begindigit = digit;
1269         }
1270
1271 out:
1272         ast_mutex_unlock(&pvt->lock);
1273
1274         return 0;
1275 }
1276
1277 static int zt_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1278 {
1279         struct zt_pvt *pvt;
1280         int res = 0;
1281         int index;
1282         int x;
1283         
1284         pvt = chan->tech_pvt;
1285
1286         ast_mutex_lock(&pvt->lock);
1287         
1288         index = zt_get_index(chan, pvt, 0);
1289
1290         if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
1291                 goto out;
1292
1293 #ifdef HAVE_PRI
1294         /* This means that the digit was already sent via PRI signalling */
1295         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
1296                         && !pvt->begindigit)
1297                 goto out;
1298 #endif
1299
1300         if (pvt->begindigit) {
1301                 x = -1;
1302                 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
1303                 res = ioctl(pvt->subs[SUB_REAL].zfd, ZT_SENDTONE, &x);
1304                 pvt->dialing = 0;
1305                 pvt->begindigit = 0;
1306         }
1307
1308 out:
1309         ast_mutex_unlock(&pvt->lock);
1310
1311         return res;
1312 }
1313
1314 static char *events[] = {
1315         "No event",
1316         "On hook",
1317         "Ring/Answered",
1318         "Wink/Flash",
1319         "Alarm",
1320         "No more alarm",
1321         "HDLC Abort",
1322         "HDLC Overrun",
1323         "HDLC Bad FCS",
1324         "Dial Complete",
1325         "Ringer On",
1326         "Ringer Off",
1327         "Hook Transition Complete",
1328         "Bits Changed",
1329         "Pulse Start",
1330         "Timer Expired",
1331         "Timer Ping",
1332         "Polarity Reversal",
1333         "Ring Begin",
1334 };
1335
1336 static struct {
1337         int alarm;
1338         char *name;
1339 } alarms[] = {
1340         { ZT_ALARM_RED, "Red Alarm" },
1341         { ZT_ALARM_YELLOW, "Yellow Alarm" },
1342         { ZT_ALARM_BLUE, "Blue Alarm" },
1343         { ZT_ALARM_RECOVER, "Recovering" },
1344         { ZT_ALARM_LOOPBACK, "Loopback" },
1345         { ZT_ALARM_NOTOPEN, "Not Open" },
1346         { ZT_ALARM_NONE, "None" },
1347 };
1348
1349 static char *alarm2str(int alarm)
1350 {
1351         int x;
1352         for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1353                 if (alarms[x].alarm & alarm)
1354                         return alarms[x].name;
1355         }
1356         return alarm ? "Unknown Alarm" : "No Alarm";
1357 }
1358
1359 static char *event2str(int event)
1360 {
1361         static char buf[256];
1362         if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1363                 return events[event];
1364         sprintf(buf, "Event %d", event); /* safe */
1365         return buf;
1366 }
1367
1368 #ifdef HAVE_PRI
1369 static char *dialplan2str(int dialplan)
1370 {
1371         if (dialplan == -1 || dialplan == -2) {
1372                 return("Dynamically set dialplan in ISDN");
1373         }
1374         return (pri_plan2str(dialplan));
1375 }
1376 #endif
1377
1378 static char *zap_sig2str(int sig)
1379 {
1380         static char buf[256];
1381         switch (sig) {
1382         case SIG_EM:
1383                 return "E & M Immediate";
1384         case SIG_EMWINK:
1385                 return "E & M Wink";
1386         case SIG_EM_E1:
1387                 return "E & M E1";
1388         case SIG_FEATD:
1389                 return "Feature Group D (DTMF)";
1390         case SIG_FEATDMF:
1391                 return "Feature Group D (MF)";
1392         case SIG_FEATDMF_TA:
1393                 return "Feature Groud D (MF) Tandem Access";
1394         case SIG_FEATB:
1395                 return "Feature Group B (MF)";
1396         case SIG_E911:
1397                 return "E911 (MF)";
1398         case SIG_FGC_CAMA:
1399                 return "FGC/CAMA (Dialpulse)";
1400         case SIG_FGC_CAMAMF:
1401                 return "FGC/CAMA (MF)";
1402         case SIG_FXSLS:
1403                 return "FXS Loopstart";
1404         case SIG_FXSGS:
1405                 return "FXS Groundstart";
1406         case SIG_FXSKS:
1407                 return "FXS Kewlstart";
1408         case SIG_FXOLS:
1409                 return "FXO Loopstart";
1410         case SIG_FXOGS:
1411                 return "FXO Groundstart";
1412         case SIG_FXOKS:
1413                 return "FXO Kewlstart";
1414         case SIG_PRI:
1415                 return "ISDN PRI";
1416         case SIG_BRI:
1417                 return "ISDN BRI Point to Point";
1418         case SIG_BRI_PTMP:
1419                 return "ISDN BRI Point to MultiPoint";
1420         case SIG_SS7:
1421                 return "SS7";
1422         case SIG_SF:
1423                 return "SF (Tone) Immediate";
1424         case SIG_SFWINK:
1425                 return "SF (Tone) Wink";
1426         case SIG_SF_FEATD:
1427                 return "SF (Tone) with Feature Group D (DTMF)";
1428         case SIG_SF_FEATDMF:
1429                 return "SF (Tone) with Feature Group D (MF)";
1430         case SIG_SF_FEATB:
1431                 return "SF (Tone) with Feature Group B (MF)";
1432         case SIG_GR303FXOKS:
1433                 return "GR-303 with FXOKS";
1434         case SIG_GR303FXSKS:
1435                 return "GR-303 with FXSKS";
1436         case 0:
1437                 return "Pseudo";
1438         default:
1439                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1440                 return buf;
1441         }
1442 }
1443
1444 #define sig2str zap_sig2str
1445
1446 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1447 {
1448         /* If the conference already exists, and we're already in it
1449            don't bother doing anything */
1450         ZT_CONFINFO zi;
1451         
1452         memset(&zi, 0, sizeof(zi));
1453         zi.chan = 0;
1454
1455         if (slavechannel > 0) {
1456                 /* If we have only one slave, do a digital mon */
1457                 zi.confmode = ZT_CONF_DIGITALMON;
1458                 zi.confno = slavechannel;
1459         } else {
1460                 if (!index) {
1461                         /* Real-side and pseudo-side both participate in conference */
1462                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1463                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1464                 } else
1465                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1466                 zi.confno = p->confno;
1467         }
1468         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1469                 return 0;
1470         if (c->zfd < 0)
1471                 return 0;
1472         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1473                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1474                 return -1;
1475         }
1476         if (slavechannel < 1) {
1477                 p->confno = zi.confno;
1478         }
1479         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1480         ast_debug(1, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1481         return 0;
1482 }
1483
1484 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1485 {
1486         /* If they're listening to our channel, they're ours */ 
1487         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1488                 return 1;
1489         /* If they're a talker on our (allocated) conference, they're ours */
1490         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1491                 return 1;
1492         return 0;
1493 }
1494
1495 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1496 {
1497         ZT_CONFINFO zi;
1498         if (/* Can't delete if there's no zfd */
1499                 (c->zfd < 0) ||
1500                 /* Don't delete from the conference if it's not our conference */
1501                 !isourconf(p, c)
1502                 /* Don't delete if we don't think it's conferenced at all (implied) */
1503                 ) return 0;
1504         memset(&zi, 0, sizeof(zi));
1505         zi.chan = 0;
1506         zi.confno = 0;
1507         zi.confmode = 0;
1508         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1509                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1510                 return -1;
1511         }
1512         ast_debug(1, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1513         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1514         return 0;
1515 }
1516
1517 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1518 {
1519         int x;
1520         int useslavenative;
1521         struct zt_pvt *slave = NULL;
1522         /* Start out optimistic */
1523         useslavenative = 1;
1524         /* Update conference state in a stateless fashion */
1525         for (x = 0; x < 3; x++) {
1526                 /* Any three-way calling makes slave native mode *definitely* out
1527                    of the question */
1528                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1529                         useslavenative = 0;
1530         }
1531         /* If we don't have any 3-way calls, check to see if we have
1532            precisely one slave */
1533         if (useslavenative) {
1534                 for (x = 0; x < MAX_SLAVES; x++) {
1535                         if (p->slaves[x]) {
1536                                 if (slave) {
1537                                         /* Whoops already have a slave!  No 
1538                                            slave native and stop right away */
1539                                         slave = NULL;
1540                                         useslavenative = 0;
1541                                         break;
1542                                 } else {
1543                                         /* We have one slave so far */
1544                                         slave = p->slaves[x];
1545                                 }
1546                         }
1547                 }
1548         }
1549         /* If no slave, slave native definitely out */
1550         if (!slave)
1551                 useslavenative = 0;
1552         else if (slave->law != p->law) {
1553                 useslavenative = 0;
1554                 slave = NULL;
1555         }
1556         if (out)
1557                 *out = slave;
1558         return useslavenative;
1559 }
1560
1561 static int reset_conf(struct zt_pvt *p)
1562 {
1563         ZT_CONFINFO zi;
1564         memset(&zi, 0, sizeof(zi));
1565         p->confno = -1;
1566         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1567         if (p->subs[SUB_REAL].zfd > -1) {
1568                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1569                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1570         }
1571         return 0;
1572 }
1573
1574 static int update_conf(struct zt_pvt *p)
1575 {
1576         int needconf = 0;
1577         int x;
1578         int useslavenative;
1579         struct zt_pvt *slave = NULL;
1580
1581         useslavenative = isslavenative(p, &slave);
1582         /* Start with the obvious, general stuff */
1583         for (x = 0; x < 3; x++) {
1584                 /* Look for three way calls */
1585                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1586                         conf_add(p, &p->subs[x], x, 0);
1587                         needconf++;
1588                 } else {
1589                         conf_del(p, &p->subs[x], x);
1590                 }
1591         }
1592         /* If we have a slave, add him to our conference now. or DAX
1593            if this is slave native */
1594         for (x = 0; x < MAX_SLAVES; x++) {
1595                 if (p->slaves[x]) {
1596                         if (useslavenative)
1597                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1598                         else {
1599                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1600                                 needconf++;
1601                         }
1602                 }
1603         }
1604         /* If we're supposed to be in there, do so now */
1605         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1606                 if (useslavenative)
1607                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1608                 else {
1609                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1610                         needconf++;
1611                 }
1612         }
1613         /* If we have a master, add ourselves to his conference */
1614         if (p->master) {
1615                 if (isslavenative(p->master, NULL)) {
1616                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1617                 } else {
1618                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1619                 }
1620         }
1621         if (!needconf) {
1622                 /* Nobody is left (or should be left) in our conference.
1623                    Kill it. */
1624                 p->confno = -1;
1625         }
1626         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1627         return 0;
1628 }
1629
1630 static void zt_enable_ec(struct zt_pvt *p)
1631 {
1632         int x;
1633         int res;
1634         if (!p)
1635                 return;
1636         if (p->echocanon) {
1637                 ast_debug(1, "Echo cancellation already on\n");
1638                 return;
1639         }
1640         if (p->digital) {
1641                 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
1642                 return;
1643         }
1644 #if defined(HAVE_ZAPTEL_ECHOCANPARAMS)
1645         if (p->echocancel.head.tap_length) {
1646 #else
1647         if (p->echocancel) {
1648 #endif
1649                 if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
1650                         x = 1;
1651                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1652                         if (res)
1653                                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
1654                 }
1655 #if defined(HAVE_ZAPTEL_ECHOCANPARAMS)
1656                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL_PARAMS, &p->echocancel);
1657 #else
1658                 x = p->echocancel;
1659                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1660 #endif
1661                 if (res)  {
1662                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
1663                 } else {
1664                         p->echocanon = 1;
1665                         ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
1666                 }
1667         } else
1668                 ast_debug(1, "No echo cancellation requested\n");
1669 }
1670
1671 static void zt_train_ec(struct zt_pvt *p)
1672 {
1673         int x;
1674         int res;
1675         
1676         if (p && p->echocanon && p->echotraining) {
1677                 x = p->echotraining;
1678                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1679                 if (res)
1680                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1681                 else
1682                         ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
1683         } else {
1684                 ast_debug(1, "No echo training requested\n");
1685         }
1686 }
1687
1688 static void zt_disable_ec(struct zt_pvt *p)
1689 {
1690         int res;
1691
1692         if (p->echocanon) {
1693 #if defined(HAVE_ZAPTEL_ECHOCANPARAMS)
1694                 struct zt_echocanparams ecp = { .tap_length = 0 };
1695
1696                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL_PARAMS, &ecp);
1697 #else
1698                 int x = 0;
1699
1700                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1701 #endif
1702
1703                 if (res)
1704                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1705                 else
1706                         ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
1707         }
1708
1709         p->echocanon = 0;
1710 }
1711
1712 static void fill_txgain(struct zt_gains *g, float gain, int law)
1713 {
1714         int j;
1715         int k;
1716         float linear_gain = pow(10.0, gain / 20.0);
1717
1718         switch (law) {
1719         case ZT_LAW_ALAW:
1720                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1721                         if (gain) {
1722                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1723                                 if (k > 32767) k = 32767;
1724                                 if (k < -32767) k = -32767;
1725                                 g->txgain[j] = AST_LIN2A(k);
1726                         } else {
1727                                 g->txgain[j] = j;
1728                         }
1729                 }
1730                 break;
1731         case ZT_LAW_MULAW:
1732                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1733                         if (gain) {
1734                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1735                                 if (k > 32767) k = 32767;
1736                                 if (k < -32767) k = -32767;
1737                                 g->txgain[j] = AST_LIN2MU(k);
1738                         } else {
1739                                 g->txgain[j] = j;
1740                         }
1741                 }
1742                 break;
1743         }
1744 }
1745
1746 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1747 {
1748         int j;
1749         int k;
1750         float linear_gain = pow(10.0, gain / 20.0);
1751
1752         switch (law) {
1753         case ZT_LAW_ALAW:
1754                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1755                         if (gain) {
1756                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1757                                 if (k > 32767) k = 32767;
1758                                 if (k < -32767) k = -32767;
1759                                 g->rxgain[j] = AST_LIN2A(k);
1760                         } else {
1761                                 g->rxgain[j] = j;
1762                         }
1763                 }
1764                 break;
1765         case ZT_LAW_MULAW:
1766                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1767                         if (gain) {
1768                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1769                                 if (k > 32767) k = 32767;
1770                                 if (k < -32767) k = -32767;
1771                                 g->rxgain[j] = AST_LIN2MU(k);
1772                         } else {
1773                                 g->rxgain[j] = j;
1774                         }
1775                 }
1776                 break;
1777         }
1778 }
1779
1780 static int set_actual_txgain(int fd, int chan, float gain, int law)
1781 {
1782         struct zt_gains g;
1783         int res;
1784
1785         memset(&g, 0, sizeof(g));
1786         g.chan = chan;
1787         res = ioctl(fd, ZT_GETGAINS, &g);
1788         if (res) {
1789                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1790                 return res;
1791         }
1792
1793         fill_txgain(&g, gain, law);
1794
1795         return ioctl(fd, ZT_SETGAINS, &g);
1796 }
1797
1798 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1799 {
1800         struct zt_gains g;
1801         int res;
1802
1803         memset(&g, 0, sizeof(g));
1804         g.chan = chan;
1805         res = ioctl(fd, ZT_GETGAINS, &g);
1806         if (res) {
1807                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1808                 return res;
1809         }
1810
1811         fill_rxgain(&g, gain, law);
1812
1813         return ioctl(fd, ZT_SETGAINS, &g);
1814 }
1815
1816 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1817 {
1818         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1819 }
1820
1821 static int bump_gains(struct zt_pvt *p)
1822 {
1823         int res;
1824
1825         /* Bump receive gain by value stored in cid_rxgain */
1826         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
1827         if (res) {
1828                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1829                 return -1;
1830         }
1831
1832         return 0;
1833 }
1834
1835 static int restore_gains(struct zt_pvt *p)
1836 {
1837         int res;
1838
1839         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1840         if (res) {
1841                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1842                 return -1;
1843         }
1844
1845         return 0;
1846 }
1847
1848 static inline int zt_set_hook(int fd, int hs)
1849 {
1850         int x, res;
1851
1852         x = hs;
1853         res = ioctl(fd, ZT_HOOK, &x);
1854
1855         if (res < 0) {
1856                 if (errno == EINPROGRESS)
1857                         return 0;
1858                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1859         }
1860
1861         return res;
1862 }
1863
1864 static inline int zt_confmute(struct zt_pvt *p, int muted)
1865 {
1866         int x, y, res;
1867         x = muted;
1868         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
1869                 y = 1;
1870                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1871                 if (res)
1872                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1873         }
1874         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1875         if (res < 0)
1876                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1877         return res;
1878 }
1879
1880 static int save_conference(struct zt_pvt *p)
1881 {
1882         struct zt_confinfo c;
1883         int res;
1884         if (p->saveconf.confmode) {
1885                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1886                 return -1;
1887         }
1888         p->saveconf.chan = 0;
1889         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1890         if (res) {
1891                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1892                 p->saveconf.confmode = 0;
1893                 return -1;
1894         }
1895         c.chan = 0;
1896         c.confno = 0;
1897         c.confmode = ZT_CONF_NORMAL;
1898         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1899         if (res) {
1900                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1901                 return -1;
1902         }
1903         ast_debug(1, "Disabled conferencing\n");
1904         return 0;
1905 }
1906
1907 /*!
1908  * \brief Send MWI state change
1909  *
1910  * \arg mailbox_full This is the mailbox associated with the FXO line that the
1911  *      MWI state has changed on.
1912  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
1913  *      whether there are messages waiting or not.
1914  *
1915  *  \return nothing
1916  *
1917  * This function does two things:
1918  *
1919  * 1) It generates an internal Asterisk event notifying any other module that
1920  *    cares about MWI that the state of a mailbox has changed.
1921  *
1922  * 2) It runs the script specified by the mwimonitornotify option to allow
1923  *    some custom handling of the state change.
1924  */
1925 static void notify_message(char *mailbox_full, int thereornot)
1926 {
1927         char s[sizeof(mwimonitornotify) + 80];
1928         struct ast_event *event;
1929         char *mailbox, *context;
1930
1931         /* Strip off @default */
1932         context = mailbox = ast_strdupa(mailbox_full);
1933         strsep(&context, "@");
1934         if (ast_strlen_zero(context))
1935                 context = "default";
1936
1937         if (!(event = ast_event_new(AST_EVENT_MWI,
1938                         AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
1939                         AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
1940                         AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
1941                         AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
1942                         AST_EVENT_IE_END))) {
1943                 return;
1944         }
1945
1946         ast_event_queue_and_cache(event,
1947                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR,
1948                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR,
1949                 AST_EVENT_IE_END);
1950
1951         if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
1952                 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
1953                 ast_safe_system(s);
1954         }
1955 }
1956
1957 static int restore_conference(struct zt_pvt *p)
1958 {
1959         int res;
1960         if (p->saveconf.confmode) {
1961                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1962                 p->saveconf.confmode = 0;
1963                 if (res) {
1964                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1965                         return -1;
1966                 }
1967         }
1968         ast_debug(1, "Restored conferencing\n");
1969         return 0;
1970 }
1971
1972 static int send_callerid(struct zt_pvt *p);
1973
1974 static int send_cwcidspill(struct zt_pvt *p)
1975 {
1976         p->callwaitcas = 0;
1977         p->cidcwexpire = 0;
1978         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1979                 return -1;
1980         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1981         /* Make sure we account for the end */
1982         p->cidlen += READ_SIZE * 4;
1983         p->cidpos = 0;
1984         send_callerid(p);
1985         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1986         return 0;
1987 }
1988
1989 static int has_voicemail(struct zt_pvt *p)
1990 {
1991         int new_msgs;
1992         struct ast_event *event;
1993         char *mailbox, *context;
1994
1995         mailbox = context = ast_strdupa(p->mailbox);
1996         strsep(&context, "@");
1997         if (ast_strlen_zero(context))
1998                 context = "default";
1999
2000         event = ast_event_get_cached(AST_EVENT_MWI,
2001                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
2002                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2003                 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
2004                 AST_EVENT_IE_END);
2005
2006         if (event) {
2007                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2008                 ast_event_destroy(event);
2009         } else
2010                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
2011
2012         return new_msgs;
2013 }
2014
2015 static int send_callerid(struct zt_pvt *p)
2016 {
2017         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
2018         int res;
2019         /* Take out of linear mode if necessary */
2020         if (p->subs[SUB_REAL].linear) {
2021                 p->subs[SUB_REAL].linear = 0;
2022                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
2023         }
2024         while (p->cidpos < p->cidlen) {
2025                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
2026                 if (res < 0) {
2027                         if (errno == EAGAIN)
2028                                 return 0;
2029                         else {
2030                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
2031                                 return -1;
2032                         }
2033                 }
2034                 if (!res)
2035                         return 0;
2036                 p->cidpos += res;
2037         }
2038         ast_free(p->cidspill);
2039         p->cidspill = NULL;
2040         if (p->callwaitcas) {
2041                 /* Wait for CID/CW to expire */
2042                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
2043         } else
2044                 restore_conference(p);
2045         return 0;
2046 }
2047
2048 static int zt_callwait(struct ast_channel *ast)
2049 {
2050         struct zt_pvt *p = ast->tech_pvt;
2051         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
2052         if (p->cidspill) {
2053                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
2054                 ast_free(p->cidspill);
2055         }
2056         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
2057                 return -1;
2058         save_conference(p);
2059         /* Silence */
2060         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
2061         if (!p->callwaitrings && p->callwaitingcallerid) {
2062                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
2063                 p->callwaitcas = 1;
2064                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
2065         } else {
2066                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
2067                 p->callwaitcas = 0;
2068                 p->cidlen = 2400 + READ_SIZE * 4;
2069         }
2070         p->cidpos = 0;
2071         send_callerid(p);
2072         
2073         return 0;
2074 }
2075
2076 #ifdef HAVE_SS7
2077 static unsigned char cid_pres2ss7pres(int cid_pres)
2078 {
2079          return (cid_pres >> 5) & 0x03;
2080 }
2081
2082 static unsigned char cid_pres2ss7screen(int cid_pres)
2083 {
2084         return cid_pres & 0x03;
2085 }
2086 #endif
2087
2088 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
2089 {
2090         struct zt_pvt *p = ast->tech_pvt;
2091         int x, res, index,mysig;
2092         char *c, *n, *l;
2093 #ifdef HAVE_PRI
2094         char *s = NULL;
2095 #endif
2096         char dest[256]; /* must be same length as p->dialdest */
2097         ast_mutex_lock(&p->lock);
2098         ast_copy_string(dest, rdest, sizeof(dest));
2099         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
2100         if ((ast->_state == AST_STATE_BUSY)) {
2101                 p->subs[SUB_REAL].needbusy = 1;
2102                 ast_mutex_unlock(&p->lock);
2103                 return 0;
2104         }
2105         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2106                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
2107                 ast_mutex_unlock(&p->lock);
2108                 return -1;
2109         }
2110         p->dialednone = 0;
2111         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
2112         {
2113                 /* Special pseudo -- automatically up */
2114                 ast_setstate(ast, AST_STATE_UP); 
2115                 ast_mutex_unlock(&p->lock);
2116                 return 0;
2117         }
2118         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
2119         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
2120         if (res)
2121                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
2122         p->outgoing = 1;
2123
2124         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
2125
2126         mysig = p->sig;
2127         if (p->outsigmod > -1)
2128                 mysig = p->outsigmod;
2129
2130         switch (mysig) {
2131         case SIG_FXOLS:
2132         case SIG_FXOGS:
2133         case SIG_FXOKS:
2134                 if (p->owner == ast) {
2135                         /* Normal ring, on hook */
2136                         
2137                         /* Don't send audio while on hook, until the call is answered */
2138                         p->dialing = 1;
2139                         if (p->use_callerid) {
2140                                 /* Generate the Caller-ID spill if desired */
2141                                 if (p->cidspill) {
2142                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
2143                                         ast_free(p->cidspill);
2144                                 }
2145                                 p->callwaitcas = 0;
2146                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
2147                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
2148                                         p->cidpos = 0;
2149                                         send_callerid(p);
2150                                 }
2151                         }
2152                         /* Choose proper cadence */
2153                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
2154                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
2155                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
2156                                 p->cidrings = cidrings[p->distinctivering - 1];
2157                         } else {
2158                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
2159                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
2160                                 p->cidrings = p->sendcalleridafter;
2161                         }
2162
2163                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
2164                         c = strchr(dest, '/');
2165                         if (c)
2166                                 c++;
2167                         if (c && (strlen(c) < p->stripmsd)) {
2168                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2169                                 c = NULL;
2170                         }
2171                         if (c) {
2172                                 p->dop.op = ZT_DIAL_OP_REPLACE;
2173                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
2174                                 ast_debug(1, "FXO: setup deferred dialstring: %s\n", c);
2175                         } else {
2176                                 p->dop.dialstr[0] = '\0';
2177                         }
2178                         x = ZT_RING;
2179                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
2180                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
2181                                 ast_mutex_unlock(&p->lock);
2182                                 return -1;
2183                         }
2184                         p->dialing = 1;
2185                 } else {
2186                         /* Call waiting call */
2187                         p->callwaitrings = 0;
2188                         if (ast->cid.cid_num)
2189                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
2190                         else
2191                                 p->callwait_num[0] = '\0';
2192                         if (ast->cid.cid_name)
2193                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
2194                         else
2195                                 p->callwait_name[0] = '\0';
2196                         /* Call waiting tone instead */
2197                         if (zt_callwait(ast)) {
2198                                 ast_mutex_unlock(&p->lock);
2199                                 return -1;
2200                         }
2201                         /* Make ring-back */
2202                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
2203                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
2204                                 
2205                 }
2206                 n = ast->cid.cid_name;
2207                 l = ast->cid.cid_num;
2208                 if (l)
2209                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
2210                 else
2211                         p->lastcid_num[0] = '\0';
2212                 if (n)
2213                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
2214                 else
2215                         p->lastcid_name[0] = '\0';
2216                 ast_setstate(ast, AST_STATE_RINGING);
2217                 index = zt_get_index(ast, p, 0);
2218                 if (index > -1) {
2219                         p->subs[index].needringing = 1;
2220                 }
2221                 break;
2222         case SIG_FXSLS:
2223         case SIG_FXSGS:
2224         case SIG_FXSKS:
2225         case SIG_EMWINK:
2226         case SIG_EM:
2227         case SIG_EM_E1:
2228         case SIG_FEATD:
2229         case SIG_FEATDMF:
2230         case SIG_E911:
2231         case SIG_FGC_CAMA:
2232         case SIG_FGC_CAMAMF:
2233         case SIG_FEATB:
2234         case SIG_SFWINK:
2235         case SIG_SF:
2236         case SIG_SF_FEATD:
2237         case SIG_SF_FEATDMF:
2238         case SIG_FEATDMF_TA:
2239         case SIG_SF_FEATB:
2240                 c = strchr(dest, '/');
2241                 if (c)
2242                         c++;
2243                 else
2244                         c = "";
2245                 if (strlen(c) < p->stripmsd) {
2246                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2247                         ast_mutex_unlock(&p->lock);
2248                         return -1;
2249                 }
2250 #ifdef HAVE_PRI
2251                 /* Start the trunk, if not GR-303 */
2252                 if (!p->pri) {
2253 #endif
2254                         x = ZT_START;
2255                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2256                         if (res < 0) {
2257                                 if (errno != EINPROGRESS) {
2258                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
2259                                         ast_mutex_unlock(&p->lock);
2260                                         return -1;
2261                                 }
2262                         }
2263 #ifdef HAVE_PRI
2264                 }
2265 #endif
2266                 ast_debug(1, "Dialing '%s'\n", c);
2267                 p->dop.op = ZT_DIAL_OP_REPLACE;
2268
2269                 c += p->stripmsd;
2270
2271                 switch (mysig) {
2272                 case SIG_FEATD:
2273                         l = ast->cid.cid_num;
2274                         if (l) 
2275                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
2276                         else
2277                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
2278                         break;
2279                 case SIG_FEATDMF:
2280                         l = ast->cid.cid_num;
2281                         if (l) 
2282                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
2283                         else
2284                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
2285                         break;
2286                 case SIG_FEATDMF_TA:
2287                 {
2288                         const char *cic, *ozz;
2289
2290                         /* If you have to go through a Tandem Access point you need to use this */
2291                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
2292                         if (!ozz)
2293                                 ozz = defaultozz;
2294                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
2295                         if (!cic)
2296                                 cic = defaultcic;
2297                         if (!ozz || !cic) {
2298                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
2299                                 ast_mutex_unlock(&p->lock);
2300                                 return -1;
2301                         }
2302                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
2303                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
2304                         p->whichwink = 0;
2305                 }
2306                         break;
2307                 case SIG_E911:
2308                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
2309                         break;
2310                 case SIG_FGC_CAMA:
2311                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2312                         break;
2313                 case SIG_FGC_CAMAMF:
2314                 case SIG_FEATB:
2315                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2316                         break;
2317                 default:
2318                         if (p->pulse)
2319                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2320                         else
2321                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2322                         break;
2323                 }
2324
2325                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2326                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2327                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2328                         p->echorest[sizeof(p->echorest) - 1] = '\0';
2329                         p->echobreak = 1;
2330                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2331                 } else
2332                         p->echobreak = 0;
2333                 if (!res) {
2334                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2335                                 x = ZT_ONHOOK;
2336                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2337                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2338                                 ast_mutex_unlock(&p->lock);
2339                                 return -1;
2340                         }
2341                 } else
2342                         ast_debug(1, "Deferring dialing...\n");
2343
2344                 p->dialing = 1;
2345                 if (ast_strlen_zero(c))
2346                         p->dialednone = 1;
2347                 ast_setstate(ast, AST_STATE_DIALING);
2348                 break;
2349         case 0:
2350                 /* Special pseudo -- automatically up*/
2351                 ast_setstate(ast, AST_STATE_UP);
2352                 break;          
2353         case SIG_PRI:
2354         case SIG_BRI:
2355         case SIG_BRI_PTMP:
2356         case SIG_SS7:
2357                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2358                 p->dialdest[0] = '\0';
2359                 break;
2360         default:
2361                 ast_debug(1, "not yet implemented\n");
2362                 ast_mutex_unlock(&p->lock);
2363                 return -1;
2364         }
2365 #ifdef HAVE_SS7
2366         if (p->ss7) {
2367                 char ss7_called_nai;
2368                 int called_nai_strip;
2369                 char ss7_calling_nai;
2370                 int calling_nai_strip;
2371                 const char *charge_str = NULL;
2372                 const char *gen_address = NULL;
2373                 const char *gen_digits = NULL;
2374                 const char *gen_dig_type = NULL;
2375                 const char *gen_dig_scheme = NULL;
2376                 const char *jip_digits = NULL;
2377                 const char *lspi_ident = NULL;
2378                 const char *rlt_flag = NULL;
2379                 const char *call_ref_id = NULL;
2380                 const char *call_ref_pc = NULL;
2381
2382                 c = strchr(dest, '/');
2383                 if (c)
2384                         c++;
2385                 else
2386                         c = dest;
2387
2388                 if (!p->hidecallerid) {
2389                         l = ast->cid.cid_num;
2390                 } else {
2391                         l = NULL;
2392                 }
2393
2394                 if (ss7_grab(p, p->ss7)) {
2395                         ast_log(LOG_WARNING, "Failed to grab SS7!\n");
2396                         ast_mutex_unlock(&p->lock);
2397                         return -1;
2398                 }
2399                 p->digital = IS_DIGITAL(ast->transfercapability);
2400                 p->ss7call = isup_new_call(p->ss7->ss7);
2401
2402                 if (!p->ss7call) {
2403                         ss7_rel(p->ss7);
2404                         ast_mutex_unlock(&p->lock);
2405                         ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
2406                         return -1;
2407                 }
2408
2409                 called_nai_strip = 0;
2410                 ss7_called_nai = p->ss7->called_nai;
2411                 if (ss7_called_nai == SS7_NAI_DYNAMIC) { /* compute dynamically */
2412                         if (strncmp(c + p->stripmsd, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2413                                 called_nai_strip = strlen(p->ss7->internationalprefix);
2414                                 ss7_called_nai = SS7_NAI_INTERNATIONAL;
2415                         } else if (strncmp(c + p->stripmsd, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2416                                 called_nai_strip = strlen(p->ss7->nationalprefix);
2417                                 ss7_called_nai = SS7_NAI_NATIONAL;
2418                         } else {
2419                                 ss7_called_nai = SS7_NAI_SUBSCRIBER;
2420                         }
2421                 }
2422                 isup_set_called(p->ss7call, c + p->stripmsd + called_nai_strip, ss7_called_nai, p->ss7->ss7);
2423
2424                 calling_nai_strip = 0;
2425                 ss7_calling_nai = p->ss7->calling_nai;
2426                 if ((l != NULL) && (ss7_calling_nai == SS7_NAI_DYNAMIC)) { /* compute dynamically */
2427                         if (strncmp(l, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2428                                 calling_nai_strip = strlen(p->ss7->internationalprefix);
2429                                 ss7_calling_nai = SS7_NAI_INTERNATIONAL;
2430                         } else if (strncmp(l, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2431                                 calling_nai_strip = strlen(p->ss7->nationalprefix);
2432                                 ss7_calling_nai = SS7_NAI_NATIONAL;
2433                         } else {
2434                                 ss7_calling_nai = SS7_NAI_SUBSCRIBER;
2435                         }
2436                 }
2437                 isup_set_calling(p->ss7call, l ? (l + calling_nai_strip) : NULL, ss7_calling_nai,
2438                         p->use_callingpres ? cid_pres2ss7pres(ast->cid.cid_pres) : (l ? SS7_PRESENTATION_ALLOWED : SS7_PRESENTATION_RESTRICTED),
2439                         p->use_callingpres ? cid_pres2ss7screen(ast->cid.cid_pres) : SS7_SCREENING_USER_PROVIDED );
2440
2441                 isup_set_oli(p->ss7call, ast->cid.cid_ani2);
2442                 isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc);
2443
2444                 /* Set the charge number if it is set */
2445                 charge_str = pbx_builtin_getvar_helper(ast, "SS7_CHARGE_NUMBER");
2446                 if (charge_str)
2447                         isup_set_charge(p->ss7call, charge_str, SS7_ANI_CALLING_PARTY_SUB_NUMBER, 0x10);
2448                 
2449                 gen_address = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_ADDRESS");
2450                 if (gen_address)
2451                         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 */
2452                 
2453                 gen_digits = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGITS");
2454                 gen_dig_type = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGTYPE");
2455                 gen_dig_scheme = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGSCHEME");
2456                 if (gen_digits)
2457                         isup_set_gen_digits(p->ss7call, gen_digits, atoi(gen_dig_type), atoi(gen_dig_scheme)); 
2458                 
2459                 jip_digits = pbx_builtin_getvar_helper(ast, "SS7_JIP");
2460                 if (jip_digits)
2461                         isup_set_jip_digits(p->ss7call, jip_digits);
2462                 
2463                 lspi_ident = pbx_builtin_getvar_helper(ast, "SS7_LSPI_IDENT");
2464                 if (lspi_ident)
2465                         isup_set_lspi(p->ss7call, lspi_ident, 0x18, 0x7, 0x00); 
2466                 
2467                 rlt_flag = pbx_builtin_getvar_helper(ast, "SS7_RLT_ON");
2468                 if ((rlt_flag) && ((strncmp("NO", rlt_flag, strlen(rlt_flag))) != 0 ))
2469                         isup_set_lspi(p->ss7call, rlt_flag, 0x18, 0x7, 0x00); /* Setting for Nortel DMS-250/500 */
2470                 
2471                 call_ref_id = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_IDENT");
2472                 call_ref_pc = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_PC");
2473                 if (call_ref_id) {
2474                         isup_set_callref(p->ss7call, atoi(call_ref_id),
2475                                          call_ref_pc ? atoi(call_ref_pc) : 0);
2476                 }
2477                 
2478                 isup_iam(p->ss7->ss7, p->ss7call);
2479                 ast_setstate(ast, AST_STATE_DIALING);
2480                 ss7_rel(p->ss7);
2481         }
2482 #endif /* HAVE_SS7 */
2483 #ifdef HAVE_PRI
2484         if (p->pri) {
2485                 struct pri_sr *sr;
2486 #ifdef SUPPORT_USERUSER
2487                 const char *useruser;
2488 #endif
2489                 int pridialplan;
2490                 int dp_strip;
2491                 int prilocaldialplan;
2492                 int ldp_strip;
2493                 int exclusive;
2494                 const char *rr_str;
2495                 int redirect_reason;
2496
2497                 c = strchr(dest, '/');
2498                 if (c)
2499                         c++;
2500                 else
2501                         c = dest;
2502
2503                 l = NULL;
2504                 n = NULL;
2505
2506                 if (!p->hidecallerid) {
2507                         l = ast->cid.cid_num;
2508                         if (!p->hidecalleridname) {
2509                                 n = ast->cid.cid_name;
2510                         }
2511                 }
2512
2513                 if (strlen(c) < p->stripmsd) {
2514                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2515                         ast_mutex_unlock(&p->lock);
2516                         return -1;
2517                 }
2518                 if (mysig != SIG_FXSKS) {
2519                         p->dop.op = ZT_DIAL_OP_REPLACE;
2520                         s = strchr(c + p->stripmsd, 'w');
2521                         if (s) {
2522                                 if (strlen(s) > 1)
2523                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2524                                 else
2525                                         p->dop.dialstr[0] = '\0';
2526                                 *s = '\0';
2527                         } else {
2528                                 p->dop.dialstr[0] = '\0';
2529                         }
2530                 }
2531                 if (pri_grab(p, p->pri)) {
2532                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2533                         ast_mutex_unlock(&p->lock);
2534                         return -1;
2535                 }
2536                 if (!(p->call = pri_new_call(p->pri->pri))) {
2537                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2538                         pri_rel(p->pri);
2539                         ast_mutex_unlock(&p->lock);
2540                         return -1;
2541                 }
2542                 if (!(sr = pri_sr_new())) {
2543                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2544                         pri_rel(p->pri);
2545                         ast_mutex_unlock(&p->lock);
2546                 }
2547                 if (p->bearer || (mysig == SIG_FXSKS)) {
2548                         if (p->bearer) {
2549                                 ast_debug(1, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
2550                                 p->bearer->call = p->call;
2551                         } else
2552                                 ast_debug(1, "I'm being setup with no bearer right now...\n");
2553
2554                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2555                 }
2556                 p->digital = IS_DIGITAL(ast->transfercapability);
2557                 /* Add support for exclusive override */
2558                 if (p->priexclusive)
2559                         exclusive = 1;
2560                 else {
2561                 /* otherwise, traditional behavior */
2562                         if (p->pri->nodetype == PRI_NETWORK)
2563                                 exclusive = 0;
2564                         else
2565                                 exclusive = 1;
2566                 }
2567                 
2568                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2569                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2570                                         (p->digital ? -1 : 
2571                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2572                 if (p->pri->facilityenable)
2573                         pri_facility_enable(p->pri->pri);
2574
2575                 ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2576                 dp_strip = 0;
2577                 pridialplan = p->pri->dialplan - 1;
2578                 if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
2579                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2580                                 if (pridialplan == -2) {
2581                                         dp_strip = strlen(p->pri->internationalprefix);
2582                                 }
2583                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2584                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2585                                 if (pridialplan == -2) {
2586                                         dp_strip = strlen(p->pri->nationalprefix);
2587                                 }
2588                                 pridialplan = PRI_NATIONAL_ISDN;
2589                         } else {
2590                                 pridialplan = PRI_LOCAL_ISDN;
2591                         }
2592                 }
2593                 while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
2594                         switch (c[p->stripmsd]) {
2595                         case 'U':
2596                                 pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
2597                                 break;
2598                         case 'I':
2599                                 pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
2600                                 break;
2601                         case 'N':
2602                                 pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
2603                                 break;
2604                         case 'L':
2605                                 pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
2606                                 break;
2607                         case 'S':
2608                                 pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
2609                                 break;
2610                         case 'V':
2611                                 pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
2612                                 break;
2613                         case 'R':
2614                                 pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
2615                                 break;
2616                         case 'u':
2617                                 pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
2618                                 break;
2619                         case 'e':
2620                                 pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
2621                                 break;
2622                         case 'x':
2623                                 pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
2624                                 break;
2625                         case 'f':
2626                                 pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
2627                                 break;
2628                         case 'n':
2629                                 pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
2630                                 break;
2631                         case 'p':
2632                                 pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
2633                                 break;
2634                         case 'r':
2635                                 pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
2636                                 break;
2637                         default:
2638                                 if (isalpha(*c))
2639                                         ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2640                         }
2641                         c++;
2642                 }
2643                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2644
2645                 ldp_strip = 0;
2646                 prilocaldialplan = p->pri->localdialplan - 1;
2647                 if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2648                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2649                                 if (prilocaldialplan == -2) {
2650                                         ldp_strip = strlen(p->pri->internationalprefix);
2651                                 }
2652                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2653                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2654                                 if (prilocaldialplan == -2) {
2655                                         ldp_strip = strlen(p->pri->nationalprefix);
2656                                 }
2657                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2658                         } else {
2659                                 prilocaldialplan = PRI_LOCAL_ISDN;
2660                         }
2661                 }
2662                 if (l != NULL) {
2663                         while (*l > '9' && *l != '*' && *l != '#') {
2664                                 switch (*l) {
2665                                 case 'U':
2666                                         prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
2667                                         break;
2668                                 case 'I':
2669                                         prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
2670                                         break;
2671                                 case 'N':
2672                                         prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
2673                                         break;
2674                                 case 'L':
2675                                         prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
2676                                         break;
2677                                 case 'S':
2678                                         prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
2679                                         break;
2680                                 case 'V':
2681                                         prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
2682                                         break;
2683                                 case 'R':
2684                                         prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
2685                                         break;
2686                                 case 'u':
2687                                         prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
2688                                         break;
2689                                 case 'e':
2690                                         prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
2691                                         break;
2692                                 case 'x':
2693                                         prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
2694                                         break;
2695                                 case 'f':
2696                                         prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
2697                                         break;
2698                                 case 'n':
2699                                         prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
2700                                         break;
2701                                 case 'p':
2702                                         prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
2703                                         break;
2704                                 case 'r':
2705                                         prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
2706                                         break;
2707                                 default:
2708                                         if (isalpha(*l))
2709                                                 ast_log(LOG_WARNING, "Unrecognized prilocaldialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2710                                 }
2711                                 l++;
2712                         }
2713                 }
2714                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2715                         p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2716                 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2717                         if (!strcasecmp(rr_str, "UNKNOWN"))
2718                                 redirect_reason = 0;
2719                         else if (!strcasecmp(rr_str, "BUSY"))
2720                                 redirect_reason = 1;
2721                         else if (!strcasecmp(rr_str, "NO_REPLY"))
2722                                 redirect_reason = 2;
2723                         else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2724                                 redirect_reason = 15;
2725                         else
2726                                 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2727                 } else
2728                         redirect_reason = PRI_REDIR_UNCONDITIONAL;
2729                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2730
2731 #ifdef SUPPORT_USERUSER
2732                 /* User-user info */
2733                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2734
2735                 if (useruser)
2736                         pri_sr_set_useruser(sr, useruser);
2737 #endif
2738
2739                 if (pri_setup(p->pri->pri, p->call, sr)) {
2740                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2741                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2742                         pri_rel(p->pri);
2743                         ast_mutex_unlock(&p->lock);
2744                         pri_sr_free(sr);
2745                         return -1;
2746                 }
2747                 pri_sr_free(sr);
2748                 ast_setstate(ast, AST_STATE_DIALING);
2749                 pri_rel(p->pri);
2750         }
2751 #endif          
2752         ast_mutex_unlock(&p->lock);
2753         return 0;
2754 }
2755
2756 static void destroy_zt_pvt(struct zt_pvt **pvt)
2757 {
2758         struct zt_pvt *p = *pvt;
2759         /* Remove channel from the list */
2760         if (p->prev)
2761                 p->prev->next = p->next;
2762         if (p->next)
2763                 p->next->prev = p->prev;
2764         if (p->use_smdi)
2765                 ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
2766         if (p->mwi_event_sub)
2767                 ast_event_unsubscribe(p->mwi_event_sub);
2768         if (p->vars)
2769                 ast_variables_destroy(p->vars);
2770         ast_mutex_destroy(&p->lock);
2771         ast_free(p);
2772         *pvt = NULL;
2773 }
2774
2775 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2776 {
2777         int owned = 0;
2778         int i = 0;
2779
2780         if (!now) {
2781                 if (cur->owner) {
2782                         owned = 1;
2783                 }
2784
2785                 for (i = 0; i < 3; i++) {
2786                         if (cur->subs[i].owner) {
2787                                 owned = 1;
2788                         }
2789                 }
2790                 if (!owned) {
2791                         if (prev) {
2792                                 prev->next = cur->next;
2793                                 if (prev->next)
2794                                         prev->next->prev = prev;
2795                                 else
2796                                         ifend = prev;
2797                         } else {
2798                                 iflist = cur->next;
2799                                 if (iflist)
2800                                         iflist->prev = NULL;
2801                                 else
2802                                         ifend = NULL;
2803                         }
2804                         if (cur->subs[SUB_REAL].zfd > -1) {
2805                                 zt_close(cur->subs[SUB_REAL].zfd);
2806                         }
2807                         destroy_zt_pvt(&cur);
2808                 }
2809         } else {
2810                 if (prev) {
2811                         prev->next = cur->next;
2812                         if (prev->next)
2813                                 prev->next->prev = prev;
2814                         else
2815                                 ifend = prev;
2816                 } else {
2817                         iflist = cur->next;
2818                         if (iflist)
2819                                 iflist->prev = NULL;
2820                         else
2821                                 ifend = NULL;
2822                 }
2823                 if (cur->subs[SUB_REAL].zfd > -1) {
2824                         zt_close(cur->subs[SUB_REAL].zfd);
2825                 }
2826                 destroy_zt_pvt(&cur);
2827         }
2828         return 0;
2829 }
2830
2831 #ifdef HAVE_PRI
2832 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2833
2834 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2835
2836 static char *zap_send_keypad_facility_descrip = 
2837 "  ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2838 "  IE over the current channel.\n";
2839
2840 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2841 {
2842         /* Data will be our digit string */
2843         struct zt_pvt *p;
2844         char *digits = (char *) data;
2845
2846         if (ast_strlen_zero(digits)) {
2847                 ast_debug(1, "No digit string sent to application!\n");
2848                 return -1;
2849         }
2850
2851         p = (struct zt_pvt *)chan->tech_pvt;
2852
2853         if (!p) {
2854                 ast_debug(1, "Unable to find technology private\n");
2855                 return -1;
2856         }
2857
2858         ast_mutex_lock(&p->lock);
2859
2860         if (!p->pri || !p->call) {
2861                 ast_debug(1, "Unable to find pri or call on channel!\n");
2862                 ast_mutex_unlock(&p->lock);
2863                 return -1;
2864         }
2865
2866         if (!pri_grab(p, p->pri)) {
2867                 pri_keypad_facility(p->pri->pri, p->call, digits);
2868                 pri_rel(p->pri);
2869         } else {
2870                 ast_debug(1, "Unable to grab pri to send keypad facility!\n");
2871                 ast_mutex_unlock(&p->lock);
2872                 return -1;
2873         }
2874
2875         ast_mutex_unlock(&p->lock);
2876
2877         return 0;
2878 }
2879
2880 static int pri_is_up(struct zt_pri *pri)
2881 {
2882         int x;
2883         for (x = 0; x < NUM_DCHANS; x++) {
2884                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2885                         return 1;
2886         }
2887         return 0;
2888 }
2889
2890 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2891 {
2892         bearer->owner = &inuse;
2893         bearer->realcall = crv;
2894         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2895         if (crv->subs[SUB_REAL].owner)
2896                 ast_channel_set_fd(crv->subs[SUB_REAL].owner, 0, crv->subs[SUB_REAL].zfd);
2897         crv->bearer = bearer;
2898         crv->call = bearer->call;
2899         crv->pri = pri;
2900         return 0;
2901 }
2902
2903 static char *pri_order(int level)
2904 {
2905         switch (level) {
2906         case 0:
2907                 return "Primary";
2908         case 1:
2909                 return "Secondary";
2910         case 2:
2911                 return "Tertiary";
2912         case 3:
2913                 return "Quaternary";
2914         default:
2915                 return "<Unknown>";
2916         }               
2917 }
2918
2919 /* Returns fd of the active dchan */
2920 static int pri_active_dchan_fd(struct zt_pri *pri)
2921 {
2922         int x = -1;
2923
2924         for (x = 0; x < NUM_DCHANS; x++) {
2925                 if ((pri->dchans[x] == pri->pri))
2926                         break;
2927         }
2928
2929         return pri->fds[x];
2930 }
2931
2932 static int pri_find_dchan(struct zt_pri *pri)
2933 {
2934         int oldslot = -1;
2935         struct pri *old;
2936         int newslot = -1;
2937         int x;
2938         old = pri->pri;
2939         for (x = 0; x < NUM_DCHANS; x++) {
2940                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2941                         newslot = x;
2942                 if (pri->dchans[x] == old) {
2943                         oldslot = x;
2944                 }
2945         }
2946         if (newslot < 0) {
2947                 newslot = 0;
2948                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2949                         pri->dchannels[newslot]);
2950         }
2951         if (old && (oldslot != newslot))
2952                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2953                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2954         pri->pri = pri->dchans[newslot];
2955         return 0;
2956 }
2957 #endif
2958
2959 static int zt_hangup(struct ast_channel *ast)
2960 {
2961         int res;
2962         int index,x, law;
2963         /*static int restore_gains(struct zt_pvt *p);*/
2964         struct zt_pvt *p = ast->tech_pvt;
2965         struct zt_pvt *tmp = NULL;
2966         struct zt_pvt *prev = NULL;
2967         ZT_PARAMS par;
2968
2969         ast_debug(1, "zt_hangup(%s)\n", ast->name);
2970         if (!ast->tech_pvt) {
2971                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2972                 return 0;
2973         }
2974         
2975         ast_mutex_lock(&p->lock);
2976         
2977         index = zt_get_index(ast, p, 1);
2978
2979         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
2980                 x = 1;
2981                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2982         }
2983
2984         x = 0;
2985         zt_confmute(p, 0);
2986         restore_gains(p);
2987         if (p->origcid_num) {
2988                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2989                 ast_free(p->origcid_num);
2990                 p->origcid_num = NULL;
2991         }       
2992         if (p->origcid_name) {
2993                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2994                 ast_free(p->origcid_name);
2995                 p->origcid_name = NULL;
2996         }       
2997         if (p->dsp)
2998                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2999         if (p->exten)
3000                 p->exten[0] = '\0';
3001
3002         ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
3003                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
3004         p->ignoredtmf = 0;
3005         
3006         if (index > -1) {
3007                 /* Real channel, do some fixup */
3008                 p->subs[index].owner = NULL;
3009                 p->subs[index].needanswer = 0;
3010                 p->subs[index].needflash = 0;
3011                 p->subs[index].needringing = 0;
3012                 p->subs[index].needbusy = 0;
3013                 p->subs[index].needcongestion = 0;
3014                 p->subs[index].linear = 0;
3015                 p->subs[index].needcallerid = 0;
3016                 p->polarity = POLARITY_IDLE;
3017                 zt_setlinear(p->subs[index].zfd, 0);
3018                 if (index == SUB_REAL) {
3019                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
3020                                 ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
3021                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
3022                                         /* We had flipped over to answer a callwait and now it's gone */
3023                                         ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
3024                                         /* Move to the call-wait, but un-own us until they flip back. */
3025                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3026                                         unalloc_sub(p, SUB_CALLWAIT);
3027                                         p->owner = NULL;
3028                                 } else {
3029                                         /* The three way hung up, but we still have a call wait */
3030                                         ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
3031                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3032                                         unalloc_sub(p, SUB_THREEWAY);
3033                                         if (p->subs[SUB_REAL].inthreeway) {
3034                                                 /* This was part of a three way call.  Immediately make way for
3035                                                    another call */
3036                                                 ast_debug(1, "Call was complete, setting owner to former third call\n");
3037                                                 p->owner = p->subs[SUB_REAL].owner;
3038                                         } else {
3039                                                 /* This call hasn't been completed yet...  Set owner to NULL */
3040                                                 ast_debug(1, "Call was incomplete, setting owner to NULL\n");
3041                                                 p->owner = NULL;
3042                                         }
3043                                         p->subs[SUB_REAL].inthreeway = 0;
3044                                 }
3045                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
3046                                 /* Move to the call-wait and switch back to them. */
3047                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3048                                 unalloc_sub(p, SUB_CALLWAIT);
3049                                 p->owner = p->subs[SUB_REAL].owner;
3050                                 if (p->owner->_state != AST_STATE_UP)
3051                                         p->subs[SUB_REAL].needanswer = 1;
3052                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
3053                                         ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
3054                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
3055                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3056                                 unalloc_sub(p, SUB_THREEWAY);
3057                                 if (p->subs[SUB_REAL].inthreeway) {
3058                                         /* This was part of a three way call.  Immediately make way for
3059                                            another call */
3060                                         ast_debug(1, "Call was complete, setting owner to former third call\n");
3061                                         p->owner = p->subs[SUB_REAL].owner;
3062                                 } else {
3063                                         /* This call hasn't been completed yet...  Set owner to NULL */
3064                                         ast_debug(1, "Call was incomplete, setting owner to NULL\n");
3065                                         p->owner = NULL;
3066                                 }
3067                                 p->subs[SUB_REAL].inthreeway = 0;
3068                         }
3069                 } else if (index == SUB_CALLWAIT) {
3070                         /* Ditch the holding callwait call, and immediately make it availabe */
3071                         if (p->subs[SUB_CALLWAIT].inthreeway) {
3072                                 /* This is actually part of a three way, placed on hold.  Place the third part
3073                                    on music on hold now */
3074                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3075                                         ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD, 
3076                                                 S_OR(p->mohsuggest, NULL),
3077                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
3078                                 }
3079                                 p->subs[SUB_THREEWAY].inthreeway = 0;
3080                                 /* Make it the call wait now */
3081                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
3082                                 unalloc_sub(p, SUB_THREEWAY);
3083                         } else
3084                                 unalloc_sub(p, SUB_CALLWAIT);
3085                 } else if (index == SUB_THREEWAY) {
3086                         if (p->subs[SUB_CALLWAIT].inthreeway) {
3087                                 /* The other party of the three way call is currently in a call-wait state.
3088                                    Start music on hold for them, and take the main guy out of the third call */
3089                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
3090                                         ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD, 
3091                                                 S_OR(p->mohsuggest, NULL),
3092                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
3093                                 }
3094                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
3095                         }
3096                         p->subs[SUB_REAL].inthreeway = 0;
3097                         /* If this was part of a three way call index, let us make
3098                            another three way call */
3099                         unalloc_sub(p, SUB_THREEWAY);
3100                 } else {
3101                         /* This wasn't any sort of call, but how are we an index? */
3102                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
3103                 }
3104         }
3105
3106         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
3107                 p->owner = NULL;
3108                 p->ringt = 0;
3109                 p->distinctivering = 0;
3110                 p->confirmanswer = 0;
3111                 p->cidrings = 1;
3112                 p->outgoing = 0;
3113                 p->digital = 0;
3114                 p->faxhandled = 0;
3115                 p->pulsedial = 0;
3116                 p->onhooktime = time(NULL);
3117 #if defined(HAVE_PRI) || defined(HAVE_SS7)
3118                 p->proceeding = 0;
3119                 p->progress = 0;
3120                 p->alerting = 0;
3121                 p->setup_ack = 0;
3122                 p->rlt = 0;
3123 #endif          
3124                 if (p->dsp) {
3125                         ast_dsp_free(p->dsp);
3126                         p->dsp = NULL;
3127                 }
3128
3129                 law = ZT_LAW_DEFAULT;
3130                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
3131                 if (res < 0) 
3132                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
3133                 /* Perform low level hangup if no owner left */
3134 #ifdef HAVE_SS7
3135                 if (p->ss7) {
3136                         if (p->ss7call) {
3137                                 if (!ss7_grab(p, p->ss7)) {
3138                                         if (!p->alreadyhungup) {
3139                                                 const char *cause = pbx_builtin_getvar_helper(ast,"SS7_CAUSE");
3140                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
3141
3142                                                 if (cause) {
3143                                                         if (atoi(cause))
3144                                                                 icause = atoi(cause);
3145                                                 }
3146                                                 isup_rel(p->ss7->ss7, p->ss7call, icause);
3147                                                 ss7_rel(p->ss7);
3148                                                 p->alreadyhungup = 1;
3149                                         } else
3150                                                 ast_log(LOG_WARNING, "Trying to hangup twice!\n");
3151                                 } else {
3152                                         ast_log(LOG_WARNING, "Unable to grab SS7 on CIC %d\n", p->cic);
3153                                         res = -1;
3154                                 }
3155                         }
3156                 }
3157 #endif
3158 #ifdef HAVE_PRI
3159                 if (p->pri) {
3160 #ifdef SUPPORT_USERUSER
3161                         const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
3162 #endif
3163
3164                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
3165                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
3166                                 if (!pri_grab(p, p->pri)) {
3167                                         if (p->alreadyhungup) {
3168                                                 ast_debug(1, "Already hungup...  Calling hangup once, and clearing call\n");
3169
3170 #ifdef SUPPORT_USERUSER
3171                                                 pri_call_set_useruser(p->call, useruser);
3172 #endif
3173
3174                                                 pri_hangup(p->pri->pri, p->call, -1);
3175                                                 p->call = NULL;
3176                                                 if (p->bearer) 
3177                                                         p->bearer->call = NULL;
3178                                         } else {
3179                                                 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
3180                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
3181                                                 ast_debug(1, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
3182
3183 #ifdef SUPPORT_USERUSER
3184                                                 pri_call_set_useruser(p->call, useruser);
3185 #endif
3186
3187                                                 p->alreadyhungup = 1;
3188                                                 if (p->bearer)
3189                                                         p->bearer->alreadyhungup = 1;
3190                                                 if (cause) {
3191                                                         if (atoi(cause))
3192                                                                 icause = atoi(cause);
3193                                                 }
3194                                                 pri_hangup(p->pri->pri, p->call, icause);
3195                                         }
3196                                         if (res < 0) 
3197                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
3198                                         pri_rel(p->pri);                        
3199                                 } else {
3200                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
3201                                         res = -1;
3202                                 }
3203                         } else {
3204                                 if (p->bearer)
3205                                         ast_debug(1, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
3206                                 p->call = NULL;
3207                                 res = 0;
3208                         }
3209                 }
3210 #endif
3211                 if (p->sig && ((p->sig != SIG_PRI) && (p->sig != SIG_SS7) && (p->sig != SIG_BRI) && (p->sig != SIG_BRI_PTMP)))
3212                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
3213                 if (res < 0) {
3214                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
3215                 }
3216                 switch (p->sig) {
3217                 case SIG_FXOGS:
3218                 case SIG_FXOLS:
3219                 case SIG_FXOKS:
3220                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
3221                         if (!res) {
3222 #if 0
3223                                 ast_debug(1, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
3224 #endif
3225                                 /* If they're off hook, try playing congestion */
3226                                 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
3227                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
3228                                 else
3229                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
3230                         }
3231                         break;
3232                 case SIG_FXSGS:
3233                 case SIG_FXSLS:
3234                 case SIG_FXSKS:
3235                         /* Make sure we're not made available for at least two seconds assuming
3236                            we were actually used for an inbound or outbound call. */
3237                         if (ast->_state != AST_STATE_RESERVED) {
3238                                 time(&p->guardtime);
3239                                 p->guardtime += 2;
3240                         }
3241                         break;
3242                 default:
3243                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
3244                 }
3245                 if (p->cidspill)
3246                         ast_free(p->cidspill);
3247                 if (p->sig)
3248                         zt_disable_ec(p);
3249                 x = 0;
3250                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
3251                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
3252                 p->didtdd = 0;
3253                 p->cidspill = NULL;
3254                 p->callwaitcas = 0;
3255                 p->callwaiting = p->permcallwaiting;
3256                 p->hidecallerid = p->permhidecallerid;
3257                 p->dialing = 0;
3258                 p->rdnis[0] = '\0';
3259                 update_conf(p);
3260                 reset_conf(p);
3261                 /* Restore data mode */
3262                 if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
3263                         x = 0;
3264                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
3265                 }
3266 #ifdef HAVE_PRI
3267                 if (p->bearer) {
3268                         ast_debug(1, "Freeing up bearer channel %d\n", p->bearer->channel);
3269                         /* Free up the bearer channel as well, and
3270                            don't use its file descriptor anymore */
3271                         update_conf(p->bearer);
3272                         reset_conf(p->bearer);
3273                         p->bearer->owner = NULL;
3274                         p->bearer->realcall = NULL;
3275                         p->bearer = NULL;
3276                         p->subs[SUB_REAL].zfd = -1;
3277                         p->pri = NULL;
3278                 }
3279 #endif
3280                 restart_monitor();
3281         }
3282
3283         p->callwaitingrepeat = 0;
3284         p->cidcwexpire = 0;
3285         p->oprmode = 0;
3286         ast->tech_pvt = NULL;
3287         ast_mutex_unlock(&p->lock);
3288         ast_module_unref(ast_module_info->self);
3289         ast_verb(3, "Hungup '%s'\n", ast->name);
3290
3291         ast_mutex_lock(&iflock);
3292         tmp = iflist;
3293         prev = NULL;
3294         if (p->destroy) {
3295                 while (tmp) {
3296                         if (tmp == p) {
3297                                 destroy_channel(prev, tmp, 0);
3298                                 break;
3299                         } else {
3300                                 prev = tmp;
3301                                 tmp = tmp->next;
3302                         }
3303                 }
3304         }
3305         ast_mutex_unlock(&iflock);
3306         return 0;
3307 }
3308
3309 static int zt_answer(struct ast_channel *ast)
3310 {
3311         struct zt_pvt *p = ast->tech_pvt;
3312         int res = 0;
3313         int index;
3314         int oldstate = ast->_state;
3315         ast_setstate(ast, AST_STATE_UP);
3316         ast_mutex_lock(&p->lock);
3317         index = zt_get_index(ast, p, 0);
3318         if (index < 0)
3319                 index = SUB_REAL;
3320         /* nothing to do if a radio channel */
3321         if ((p->radio || (p->oprmode < 0))) {
3322                 ast_mutex_unlock(&p->lock);
3323                 return 0;
3324         }
3325         switch (p->sig) {
3326         case SIG_FXSLS:
3327         case SIG_FXSGS:
3328         case SIG_FXSKS:
3329                 p->ringt = 0;
3330                 /* Fall through */
3331         case SIG_EM:
3332         case SIG_EM_E1:
3333         case SIG_EMWINK:
3334         case SIG_FEATD:
3335         case SIG_FEATDMF:
3336         case SIG_FEATDMF_TA:
3337         case SIG_E911:
3338         case SIG_FGC_CAMA:
3339         case SIG_FGC_CAMAMF:
3340         case SIG_FEATB:
3341         case SIG_SF:
3342         case SIG_SFWINK:
3343         case SIG_SF_FEATD:
3344         case SIG_SF_FEATDMF:
3345         case SIG_SF_FEATB:
3346         case SIG_FXOLS:
3347         case SIG_FXOGS:
3348         case SIG_FXOKS:
3349                 /* Pick up the line */
3350                 ast_debug(1, "Took %s off hook\n", ast->name);
3351                 if (p->hanguponpolarityswitch) {
3352                         p->polaritydelaytv = ast_tvnow();
3353                 }
3354                 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
3355                 tone_zone_play_tone(p->subs[index].zfd, -1);
3356                 p->dialing = 0;
3357                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
3358                         if (oldstate == AST_STATE_RINGING) {
3359                                 ast_debug(1, "Finally swapping real and threeway\n");
3360                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
3361                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3362                                 p->owner = p->subs[SUB_REAL].owner;
3363                         }
3364                 }
3365                 if (p->sig & __ZT_SIG_FXS) {
3366                         zt_enable_ec(p);
3367                         zt_train_ec(p);
3368                 }
3369                 break;
3370 #ifdef HAVE_PRI
3371         case SIG_BRI:
3372         case SIG_BRI_PTMP:
3373         case SIG_PRI:
3374                 /* Send a pri acknowledge */
3375                 if (!pri_grab(p, p->pri)) {
3376                         p->proceeding = 1;
3377                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
3378                         pri_rel(p->pri);
3379                 } else {
3380                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
3381                         res = -1;
3382                 }
3383                 break;
3384 #endif
3385 #ifdef HAVE_SS7
3386         case SIG_SS7:
3387                 if (!ss7_grab(p, p->ss7)) {
3388                         p->proceeding = 1;
3389                         res = isup_anm(p->ss7->ss7, p->ss7call);
3390                         ss7_rel(p->ss7);
3391                 } else {
3392                         ast_log(LOG_WARNING, "Unable to grab SS7 on span %d\n", p->span);
3393                         res = -1;
3394                 }
3395                 break;
3396 #endif
3397         case 0:
3398                 ast_mutex_unlock(&p->lock);
3399                 return 0;
3400         default:
3401                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
3402                 res = -1;
3403         }
3404         ast_mutex_unlock(&p->lock);
3405         return res;
3406 }
3407
3408 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
3409 {
3410         char *cp;
3411         signed char *scp;
3412         int x;
3413         int index;
3414         struct zt_pvt *p = chan->tech_pvt, *pp;
3415         struct oprmode *oprmode;
3416         
3417
3418         /* all supported options require data */
3419         if (!data || (datalen < 1)) {
3420                 errno = EINVAL;
3421                 return -1;
3422         }
3423
3424         switch (option) {
3425         case AST_OPTION_TXGAIN:
3426                 scp = (signed char *) data;
3427                 index = zt_get_index(chan, p, 0);
3428                 if (index < 0) {
3429                         ast_log(LOG_WARNING, "No index in TXGAIN?\n");
3430                         return -1;
3431                 }
3432                 ast_debug(1, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
3433                 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
3434         case AST_OPTION_RXGAIN:
3435                 scp = (signed char *) data;
3436                 index = zt_get_index(chan, p, 0);
3437                 if (index < 0) {
3438                         ast_log(LOG_WARNING, "No index in RXGAIN?\n");
3439                         return -1;
3440                 }
3441                 ast_debug(1, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
3442                 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
3443         case AST_OPTION_TONE_VERIFY:
3444                 if (!p->dsp)
3445                         break;
3446                 cp = (char *) data;
3447                 switch (*cp) {
3448                 case 1:
3449                         ast_debug(1, "Set option TONE VERIFY, mode: MUTECONF(1) on