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