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