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