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