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