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