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