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