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