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