Merged revisions 67457 via svnmerge from
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Zaptel Pseudo TDM interface 
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * Connects to the zaptel telephony library as well as 
26  * libpri. Libpri is optional and needed only if you are
27  * going to use ISDN connections.
28  *
29  * You need to install libraries before you attempt to compile
30  * and install the zaptel channel.
31  *
32  * \par See also
33  * \arg \ref Config_zap
34  *
35  * \ingroup channel_drivers
36  *
37  * \todo Deprecate the "musiconhold" configuration option post 1.4
38  */
39
40 /*** MODULEINFO
41         <depend>res_smdi</depend>
42         <depend>zaptel_vldtmf</depend>
43         <depend>zaptel</depend>
44         <depend>tonezone</depend>
45         <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 if (option_debug)
1573                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1574 }
1575
1576 static void zt_train_ec(struct zt_pvt *p)
1577 {
1578         int x;
1579         int res;
1580         if (p && p->echocancel && p->echotraining) {
1581                 x = p->echotraining;
1582                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1583                 if (res)
1584                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1585                 else {
1586                         if (option_debug)
1587                                 ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1588                 }
1589         } else {
1590                 if (option_debug)
1591                         ast_log(LOG_DEBUG, "No echo training requested\n");
1592         }
1593 }
1594
1595 static void zt_disable_ec(struct zt_pvt *p)
1596 {
1597         int x;
1598         int res;
1599         if (p->echocancel) {
1600                 x = 0;
1601                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1602                 if (res)
1603                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1604                 else if (option_debug)
1605                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1606         }
1607         p->echocanon = 0;
1608 }
1609
1610 static void fill_txgain(struct zt_gains *g, float gain, int law)
1611 {
1612         int j;
1613         int k;
1614         float linear_gain = pow(10.0, gain / 20.0);
1615
1616         switch (law) {
1617         case ZT_LAW_ALAW:
1618                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1619                         if (gain) {
1620                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1621                                 if (k > 32767) k = 32767;
1622                                 if (k < -32767) k = -32767;
1623                                 g->txgain[j] = AST_LIN2A(k);
1624                         } else {
1625                                 g->txgain[j] = j;
1626                         }
1627                 }
1628                 break;
1629         case ZT_LAW_MULAW:
1630                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1631                         if (gain) {
1632                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1633                                 if (k > 32767) k = 32767;
1634                                 if (k < -32767) k = -32767;
1635                                 g->txgain[j] = AST_LIN2MU(k);
1636                         } else {
1637                                 g->txgain[j] = j;
1638                         }
1639                 }
1640                 break;
1641         }
1642 }
1643
1644 static void fill_rxgain(struct zt_gains *g, float gain, int law)
1645 {
1646         int j;
1647         int k;
1648         float linear_gain = pow(10.0, gain / 20.0);
1649
1650         switch (law) {
1651         case ZT_LAW_ALAW:
1652                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1653                         if (gain) {
1654                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1655                                 if (k > 32767) k = 32767;
1656                                 if (k < -32767) k = -32767;
1657                                 g->rxgain[j] = AST_LIN2A(k);
1658                         } else {
1659                                 g->rxgain[j] = j;
1660                         }
1661                 }
1662                 break;
1663         case ZT_LAW_MULAW:
1664                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1665                         if (gain) {
1666                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1667                                 if (k > 32767) k = 32767;
1668                                 if (k < -32767) k = -32767;
1669                                 g->rxgain[j] = AST_LIN2MU(k);
1670                         } else {
1671                                 g->rxgain[j] = j;
1672                         }
1673                 }
1674                 break;
1675         }
1676 }
1677
1678 static int set_actual_txgain(int fd, int chan, float gain, int law)
1679 {
1680         struct zt_gains g;
1681         int res;
1682
1683         memset(&g, 0, sizeof(g));
1684         g.chan = chan;
1685         res = ioctl(fd, ZT_GETGAINS, &g);
1686         if (res) {
1687                 if (option_debug)
1688                         ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1689                 return res;
1690         }
1691
1692         fill_txgain(&g, gain, law);
1693
1694         return ioctl(fd, ZT_SETGAINS, &g);
1695 }
1696
1697 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1698 {
1699         struct zt_gains g;
1700         int res;
1701
1702         memset(&g, 0, sizeof(g));
1703         g.chan = chan;
1704         res = ioctl(fd, ZT_GETGAINS, &g);
1705         if (res) {
1706                 if (option_debug)
1707                         ast_log(LOG_DEBUG, "Failed to read gains: %s\n", strerror(errno));
1708                 return res;
1709         }
1710
1711         fill_rxgain(&g, gain, law);
1712
1713         return ioctl(fd, ZT_SETGAINS, &g);
1714 }
1715
1716 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1717 {
1718         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1719 }
1720
1721 static int bump_gains(struct zt_pvt *p)
1722 {
1723         int res;
1724
1725         /* Bump receive gain by value stored in cid_rxgain */
1726         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
1727         if (res) {
1728                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1729                 return -1;
1730         }
1731
1732         return 0;
1733 }
1734
1735 static int restore_gains(struct zt_pvt *p)
1736 {
1737         int res;
1738
1739         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1740         if (res) {
1741                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1742                 return -1;
1743         }
1744
1745         return 0;
1746 }
1747
1748 static inline int zt_set_hook(int fd, int hs)
1749 {
1750         int x, res;
1751         x = hs;
1752         res = ioctl(fd, ZT_HOOK, &x);
1753         if (res < 0) 
1754         {
1755                 if (errno == EINPROGRESS) return 0;
1756                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1757         }
1758         return res;
1759 }
1760
1761 static inline int zt_confmute(struct zt_pvt *p, int muted)
1762 {
1763         int x, y, res;
1764         x = muted;
1765         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
1766                 y = 1;
1767                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1768                 if (res)
1769                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1770         }
1771         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1772         if (res < 0)
1773                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1774         return res;
1775 }
1776
1777 static int save_conference(struct zt_pvt *p)
1778 {
1779         struct zt_confinfo c;
1780         int res;
1781         if (p->saveconf.confmode) {
1782                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1783                 return -1;
1784         }
1785         p->saveconf.chan = 0;
1786         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1787         if (res) {
1788                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1789                 p->saveconf.confmode = 0;
1790                 return -1;
1791         }
1792         c.chan = 0;
1793         c.confno = 0;
1794         c.confmode = ZT_CONF_NORMAL;
1795         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1796         if (res) {
1797                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1798                 return -1;
1799         }
1800         if (option_debug)
1801                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1802         return 0;
1803 }
1804
1805 static int restore_conference(struct zt_pvt *p)
1806 {
1807         int res;
1808         if (p->saveconf.confmode) {
1809                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1810                 p->saveconf.confmode = 0;
1811                 if (res) {
1812                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1813                         return -1;
1814                 }
1815         }
1816         if (option_debug)
1817                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1818         return 0;
1819 }
1820
1821 static int send_callerid(struct zt_pvt *p);
1822
1823 static int send_cwcidspill(struct zt_pvt *p)
1824 {
1825         p->callwaitcas = 0;
1826         p->cidcwexpire = 0;
1827         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1828                 return -1;
1829         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1830         /* Make sure we account for the end */
1831         p->cidlen += READ_SIZE * 4;
1832         p->cidpos = 0;
1833         send_callerid(p);
1834         if (option_verbose > 2)
1835                 ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1836         return 0;
1837 }
1838
1839 static int has_voicemail(struct zt_pvt *p)
1840 {
1841         int new_msgs;
1842         struct ast_event *event;
1843
1844         event = ast_event_get_cached(AST_EVENT_MWI,
1845                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, p->mailbox,
1846                 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
1847                 AST_EVENT_IE_END);
1848
1849         if (event) {
1850                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
1851                 ast_event_destroy(event);
1852         } else
1853                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
1854
1855         return new_msgs;
1856 }
1857
1858 static int send_callerid(struct zt_pvt *p)
1859 {
1860         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1861         int res;
1862         /* Take out of linear mode if necessary */
1863         if (p->subs[SUB_REAL].linear) {
1864                 p->subs[SUB_REAL].linear = 0;
1865                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1866         }
1867         while (p->cidpos < p->cidlen) {
1868                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1869                 if (res < 0) {
1870                         if (errno == EAGAIN)
1871                                 return 0;
1872                         else {
1873                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1874                                 return -1;
1875                         }
1876                 }
1877                 if (!res)
1878                         return 0;
1879                 p->cidpos += res;
1880         }
1881         free(p->cidspill);
1882         p->cidspill = NULL;
1883         if (p->callwaitcas) {
1884                 /* Wait for CID/CW to expire */
1885                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1886         } else
1887                 restore_conference(p);
1888         return 0;
1889 }
1890
1891 static int zt_callwait(struct ast_channel *ast)
1892 {
1893         struct zt_pvt *p = ast->tech_pvt;
1894         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1895         if (p->cidspill) {
1896                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1897                 free(p->cidspill);
1898         }
1899         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1900                 return -1;
1901         save_conference(p);
1902         /* Silence */
1903         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1904         if (!p->callwaitrings && p->callwaitingcallerid) {
1905                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1906                 p->callwaitcas = 1;
1907                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1908         } else {
1909                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1910                 p->callwaitcas = 0;
1911                 p->cidlen = 2400 + READ_SIZE * 4;
1912         }
1913         p->cidpos = 0;
1914         send_callerid(p);
1915         
1916         return 0;
1917 }
1918
1919 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1920 {
1921         struct zt_pvt *p = ast->tech_pvt;
1922         int x, res, index,mysig;
1923         char *c, *n, *l;
1924 #ifdef HAVE_PRI
1925         char *s = NULL;
1926 #endif
1927         char dest[256]; /* must be same length as p->dialdest */
1928         ast_mutex_lock(&p->lock);
1929         ast_copy_string(dest, rdest, sizeof(dest));
1930         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1931         if ((ast->_state == AST_STATE_BUSY)) {
1932                 p->subs[SUB_REAL].needbusy = 1;
1933                 ast_mutex_unlock(&p->lock);
1934                 return 0;
1935         }
1936         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1937                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1938                 ast_mutex_unlock(&p->lock);
1939                 return -1;
1940         }
1941         p->dialednone = 0;
1942         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
1943         {
1944                 /* Special pseudo -- automatically up */
1945                 ast_setstate(ast, AST_STATE_UP); 
1946                 ast_mutex_unlock(&p->lock);
1947                 return 0;
1948         }
1949         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1950         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1951         if (res)
1952                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1953         p->outgoing = 1;
1954
1955         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1956
1957         mysig = p->sig;
1958         if (p->outsigmod > -1)
1959                 mysig = p->outsigmod;
1960
1961         switch (mysig) {
1962         case SIG_FXOLS:
1963         case SIG_FXOGS:
1964         case SIG_FXOKS:
1965                 if (p->owner == ast) {
1966                         /* Normal ring, on hook */
1967                         
1968                         /* Don't send audio while on hook, until the call is answered */
1969                         p->dialing = 1;
1970                         if (p->use_callerid) {
1971                                 /* Generate the Caller-ID spill if desired */
1972                                 if (p->cidspill) {
1973                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1974                                         free(p->cidspill);
1975                                 }
1976                                 p->callwaitcas = 0;
1977                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1978                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1979                                         p->cidpos = 0;
1980                                         send_callerid(p);
1981                                 }
1982                         }
1983                         /* Choose proper cadence */
1984                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1985                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering - 1]))
1986                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1987                                 p->cidrings = cidrings[p->distinctivering - 1];
1988                         } else {
1989                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1990                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1991                                 p->cidrings = p->sendcalleridafter;
1992                         }
1993
1994                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1995                         c = strchr(dest, '/');
1996                         if (c)
1997                                 c++;
1998                         if (c && (strlen(c) < p->stripmsd)) {
1999                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2000                                 c = NULL;
2001                         }
2002                         if (c) {
2003                                 p->dop.op = ZT_DIAL_OP_REPLACE;
2004                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
2005                                 if (option_debug)
2006                                         ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
2007                         } else {
2008                                 p->dop.dialstr[0] = '\0';
2009                         }
2010                         x = ZT_RING;
2011                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
2012                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
2013                                 ast_mutex_unlock(&p->lock);
2014                                 return -1;
2015                         }
2016                         p->dialing = 1;
2017                 } else {
2018                         /* Call waiting call */
2019                         p->callwaitrings = 0;
2020                         if (ast->cid.cid_num)
2021                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
2022                         else
2023                                 p->callwait_num[0] = '\0';
2024                         if (ast->cid.cid_name)
2025                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
2026                         else
2027                                 p->callwait_name[0] = '\0';
2028                         /* Call waiting tone instead */
2029                         if (zt_callwait(ast)) {
2030                                 ast_mutex_unlock(&p->lock);
2031                                 return -1;
2032                         }
2033                         /* Make ring-back */
2034                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
2035                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
2036                                 
2037                 }
2038                 n = ast->cid.cid_name;
2039                 l = ast->cid.cid_num;
2040                 if (l)
2041                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
2042                 else
2043                         p->lastcid_num[0] = '\0';
2044                 if (n)
2045                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
2046                 else
2047                         p->lastcid_name[0] = '\0';
2048                 ast_setstate(ast, AST_STATE_RINGING);
2049                 index = zt_get_index(ast, p, 0);
2050                 if (index > -1) {
2051                         p->subs[index].needringing = 1;
2052                 }
2053                 break;
2054         case SIG_FXSLS:
2055         case SIG_FXSGS:
2056         case SIG_FXSKS:
2057         case SIG_EMWINK:
2058         case SIG_EM:
2059         case SIG_EM_E1:
2060         case SIG_FEATD:
2061         case SIG_FEATDMF:
2062         case SIG_E911:
2063         case SIG_FGC_CAMA:
2064         case SIG_FGC_CAMAMF:
2065         case SIG_FEATB:
2066         case SIG_SFWINK:
2067         case SIG_SF:
2068         case SIG_SF_FEATD:
2069         case SIG_SF_FEATDMF:
2070         case SIG_FEATDMF_TA:
2071         case SIG_SF_FEATB:
2072                 c = strchr(dest, '/');
2073                 if (c)
2074                         c++;
2075                 else
2076                         c = "";
2077                 if (strlen(c) < p->stripmsd) {
2078                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2079                         ast_mutex_unlock(&p->lock);
2080                         return -1;
2081                 }
2082 #ifdef HAVE_PRI
2083                 /* Start the trunk, if not GR-303 */
2084                 if (!p->pri) {
2085 #endif
2086                         x = ZT_START;
2087                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2088                         if (res < 0) {
2089                                 if (errno != EINPROGRESS) {
2090                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
2091                                         ast_mutex_unlock(&p->lock);
2092                                         return -1;
2093                                 }
2094                         }
2095 #ifdef HAVE_PRI
2096                 }
2097 #endif
2098                 if (option_debug)
2099                         ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
2100                 p->dop.op = ZT_DIAL_OP_REPLACE;
2101
2102                 c += p->stripmsd;
2103
2104                 switch (mysig) {
2105                 case SIG_FEATD:
2106                         l = ast->cid.cid_num;
2107                         if (l) 
2108                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
2109                         else
2110                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
2111                         break;
2112                 case SIG_FEATDMF:
2113                         l = ast->cid.cid_num;
2114                         if (l) 
2115                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
2116                         else
2117                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
2118                         break;
2119                 case SIG_FEATDMF_TA:
2120                 {
2121                         const char *cic, *ozz;
2122
2123                         /* If you have to go through a Tandem Access point you need to use this */
2124                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
2125                         if (!ozz)
2126                                 ozz = defaultozz;
2127                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
2128                         if (!cic)
2129                                 cic = defaultcic;
2130                         if (!ozz || !cic) {
2131                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
2132                                 ast_mutex_unlock(&p->lock);
2133                                 return -1;
2134                         }
2135                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
2136                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
2137                         p->whichwink = 0;
2138                 }
2139                         break;
2140                 case SIG_E911:
2141                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
2142                         break;
2143                 case SIG_FGC_CAMA:
2144                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2145                         break;
2146                 case SIG_FGC_CAMAMF:
2147                 case SIG_FEATB:
2148                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2149                         break;
2150                 default:
2151                         if (p->pulse)
2152                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2153                         else
2154                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2155                         break;
2156                 }
2157
2158                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2159                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2160                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2161                         p->echorest[sizeof(p->echorest) - 1] = '\0';
2162                         p->echobreak = 1;
2163                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2164                 } else
2165                         p->echobreak = 0;
2166                 if (!res) {
2167                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2168                                 x = ZT_ONHOOK;
2169                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2170                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2171                                 ast_mutex_unlock(&p->lock);
2172                                 return -1;
2173                         }
2174                 } else {
2175                         if (option_debug)
2176                                 ast_log(LOG_DEBUG, "Deferring dialing...\n");
2177                 }
2178                 p->dialing = 1;
2179                 if (ast_strlen_zero(c))
2180                         p->dialednone = 1;
2181                 ast_setstate(ast, AST_STATE_DIALING);
2182                 break;
2183         case 0:
2184                 /* Special pseudo -- automatically up*/
2185                 ast_setstate(ast, AST_STATE_UP);
2186                 break;          
2187         case SIG_PRI:
2188         case SIG_SS7:
2189                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2190                 p->dialdest[0] = '\0';
2191                 break;
2192         default:
2193                 if (option_debug)
2194                         ast_log(LOG_DEBUG, "not yet implemented\n");
2195                 ast_mutex_unlock(&p->lock);
2196                 return -1;
2197         }
2198 #ifdef HAVE_SS7
2199         if (p->ss7) {
2200                 c = strchr(dest, '/');
2201                 if (c)
2202                         c++;
2203                 else
2204                         c = dest;
2205
2206                 if (!p->hidecallerid) {
2207                         l = ast->cid.cid_num;
2208                 } else {
2209                         l = NULL;
2210                 }
2211
2212                 ss7_grab(p, p->ss7);
2213                 p->digital = IS_DIGITAL(ast->transfercapability);
2214                 p->ss7call = isup_new_call(p->ss7->ss7);
2215
2216                 if (!p->ss7call) {
2217                         ss7_rel(p->ss7);
2218                         ast_mutex_unlock(&p->lock);
2219                         ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
2220                         return -1;
2221                 }
2222
2223                 isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc, c + p->stripmsd, l);
2224
2225                 isup_iam(p->ss7->ss7, p->ss7call);
2226                 ss7_rel(p->ss7);
2227         }
2228 #endif /* HAVE_SS7 */
2229 #ifdef HAVE_PRI
2230         if (p->pri) {
2231                 struct pri_sr *sr;
2232 #ifdef SUPPORT_USERUSER
2233                 const char *useruser;
2234 #endif
2235                 int pridialplan;
2236                 int dp_strip;
2237                 int prilocaldialplan;
2238                 int ldp_strip;
2239                 int exclusive;
2240                 const char *rr_str;
2241                 int redirect_reason;
2242
2243                 c = strchr(dest, '/');
2244                 if (c)
2245                         c++;
2246                 else
2247                         c = dest;
2248                 if (!p->hidecalleridname)
2249                         n = ast->cid.cid_name;
2250                 else
2251                         n = NULL;
2252                 if (!p->hidecallerid) {
2253                         l = ast->cid.cid_num;
2254                         n = ast->cid.cid_name;
2255                 } else {
2256                         l = NULL;
2257                         n = NULL;
2258                 }
2259                 if (strlen(c) < p->stripmsd) {
2260                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2261                         ast_mutex_unlock(&p->lock);
2262                         return -1;
2263                 }
2264                 if (mysig != SIG_FXSKS) {
2265                         p->dop.op = ZT_DIAL_OP_REPLACE;
2266                         s = strchr(c + p->stripmsd, 'w');
2267                         if (s) {
2268                                 if (strlen(s) > 1)
2269                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2270                                 else
2271                                         p->dop.dialstr[0] = '\0';
2272                                 *s = '\0';
2273                         } else {
2274                                 p->dop.dialstr[0] = '\0';
2275                         }
2276                 }
2277                 if (pri_grab(p, p->pri)) {
2278                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2279                         ast_mutex_unlock(&p->lock);
2280                         return -1;
2281                 }
2282                 if (!(p->call = pri_new_call(p->pri->pri))) {
2283                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2284                         pri_rel(p->pri);
2285                         ast_mutex_unlock(&p->lock);
2286                         return -1;
2287                 }
2288                 if (!(sr = pri_sr_new())) {
2289                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2290                         pri_rel(p->pri);
2291                         ast_mutex_unlock(&p->lock);
2292                 }
2293                 if (p->bearer || (mysig == SIG_FXSKS)) {
2294                         if (p->bearer) {
2295                                 if (option_debug)
2296                                         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);
2297                                 p->bearer->call = p->call;
2298                         } else {
2299                                 if (option_debug)
2300                                         ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
2301                         }
2302                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2303                 }
2304                 p->digital = IS_DIGITAL(ast->transfercapability);
2305                 /* Add support for exclusive override */
2306                 if (p->priexclusive)
2307                         exclusive = 1;
2308                 else {
2309                 /* otherwise, traditional behavior */
2310                         if (p->pri->nodetype == PRI_NETWORK)
2311                                 exclusive = 0;
2312                         else
2313                                 exclusive = 1;
2314                 }
2315                 
2316                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2317                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2318                                         (p->digital ? -1 : 
2319                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2320                 if (p->pri->facilityenable)
2321                         pri_facility_enable(p->pri->pri);
2322
2323                 if (option_verbose > 2)
2324                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2325                 dp_strip = 0;
2326                 pridialplan = p->pri->dialplan - 1;
2327                 if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
2328                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2329                                 if (pridialplan == -2) {
2330                                         dp_strip = strlen(p->pri->internationalprefix);
2331                                 }
2332                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2333                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2334                                 if (pridialplan == -2) {
2335                                         dp_strip = strlen(p->pri->nationalprefix);
2336                                 }
2337                                 pridialplan = PRI_NATIONAL_ISDN;
2338                         } else {
2339                                 pridialplan = PRI_LOCAL_ISDN;
2340                         }
2341                 }
2342                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2343
2344                 ldp_strip = 0;
2345                 prilocaldialplan = p->pri->localdialplan - 1;
2346                 if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2347                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2348                                 if (prilocaldialplan == -2) {
2349                                         ldp_strip = strlen(p->pri->internationalprefix);
2350                                 }
2351                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2352                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2353                                 if (prilocaldialplan == -2) {
2354                                         ldp_strip = strlen(p->pri->nationalprefix);
2355                                 }
2356                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2357                         } else {
2358                                 prilocaldialplan = PRI_LOCAL_ISDN;
2359                         }
2360                 }
2361                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2362                         p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2363                 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2364                         if (!strcasecmp(rr_str, "UNKNOWN"))
2365                                 redirect_reason = 0;
2366                         else if (!strcasecmp(rr_str, "BUSY"))
2367                                 redirect_reason = 1;
2368                         else if (!strcasecmp(rr_str, "NO_REPLY"))
2369                                 redirect_reason = 2;
2370                         else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2371                                 redirect_reason = 15;
2372                         else
2373                                 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2374                 } else
2375                         redirect_reason = PRI_REDIR_UNCONDITIONAL;
2376                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2377
2378 #ifdef SUPPORT_USERUSER
2379                 /* User-user info */
2380                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2381
2382                 if (useruser)
2383                         pri_sr_set_useruser(sr, useruser);
2384 #endif
2385
2386                 if (pri_setup(p->pri->pri, p->call, sr)) {
2387                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2388                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2389                         pri_rel(p->pri);
2390                         ast_mutex_unlock(&p->lock);
2391                         pri_sr_free(sr);
2392                         return -1;
2393                 }
2394                 pri_sr_free(sr);
2395                 ast_setstate(ast, AST_STATE_DIALING);
2396                 pri_rel(p->pri);
2397         }
2398 #endif          
2399         ast_mutex_unlock(&p->lock);
2400         return 0;
2401 }
2402
2403 static void destroy_zt_pvt(struct zt_pvt **pvt)
2404 {
2405         struct zt_pvt *p = *pvt;
2406         /* Remove channel from the list */
2407         if (p->prev)
2408                 p->prev->next = p->next;
2409         if (p->next)
2410                 p->next->prev = p->prev;
2411         if (p->use_smdi)
2412                 ASTOBJ_UNREF(p->smdi_iface, ast_smdi_interface_destroy);
2413         if (p->mwi_event_sub)
2414                 ast_event_unsubscribe(p->mwi_event_sub);
2415         ast_mutex_destroy(&p->lock);
2416         free(p);
2417         *pvt = NULL;
2418 }
2419
2420 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
2421 {
2422         int owned = 0;
2423         int i = 0;
2424
2425         if (!now) {
2426                 if (cur->owner) {
2427                         owned = 1;
2428                 }
2429
2430                 for (i = 0; i < 3; i++) {
2431                         if (cur->subs[i].owner) {
2432                                 owned = 1;
2433                         }
2434                 }
2435                 if (!owned) {
2436                         if (prev) {
2437                                 prev->next = cur->next;
2438                                 if (prev->next)
2439                                         prev->next->prev = prev;
2440                                 else
2441                                         ifend = prev;
2442                         } else {
2443                                 iflist = cur->next;
2444                                 if (iflist)
2445                                         iflist->prev = NULL;
2446                                 else
2447                                         ifend = NULL;
2448                         }
2449                         if (cur->subs[SUB_REAL].zfd > -1) {
2450                                 zt_close(cur->subs[SUB_REAL].zfd);
2451                         }
2452                         destroy_zt_pvt(&cur);
2453                 }
2454         } else {
2455                 if (prev) {
2456                         prev->next = cur->next;
2457                         if (prev->next)
2458                                 prev->next->prev = prev;
2459                         else
2460                                 ifend = prev;
2461                 } else {
2462                         iflist = cur->next;
2463                         if (iflist)
2464                                 iflist->prev = NULL;
2465                         else
2466                                 ifend = NULL;
2467                 }
2468                 if (cur->subs[SUB_REAL].zfd > -1) {
2469                         zt_close(cur->subs[SUB_REAL].zfd);
2470                 }
2471                 destroy_zt_pvt(&cur);
2472         }
2473         return 0;
2474 }
2475
2476 #ifdef HAVE_PRI
2477 static char *zap_send_keypad_facility_app = "ZapSendKeypadFacility";
2478
2479 static char *zap_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2480
2481 static char *zap_send_keypad_facility_descrip = 
2482 "  ZapSendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2483 "  IE over the current channel.\n";
2484
2485 static int zap_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2486 {
2487         /* Data will be our digit string */
2488         struct zt_pvt *p;
2489         char *digits = (char *) data;
2490
2491         if (ast_strlen_zero(digits)) {
2492                 if (option_debug)
2493                         ast_log(LOG_DEBUG, "No digit string sent to application!\n");
2494                 return -1;
2495         }
2496
2497         p = (struct zt_pvt *)chan->tech_pvt;
2498
2499         if (!p) {
2500                 if (option_debug)
2501                         ast_log(LOG_DEBUG, "Unable to find technology private\n");
2502                 return -1;
2503         }
2504
2505         ast_mutex_lock(&p->lock);
2506
2507         if (!p->pri || !p->call) {
2508                 if (option_debug)
2509                         ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
2510                 ast_mutex_unlock(&p->lock);
2511                 return -1;
2512         }
2513
2514         if (!pri_grab(p, p->pri)) {
2515                 pri_keypad_facility(p->pri->pri, p->call, digits);
2516                 pri_rel(p->pri);
2517         } else {
2518                 if (option_debug)
2519                         ast_log(LOG_DEBUG, "Unable to grab pri to send keypad facility!\n");
2520                 ast_mutex_unlock(&p->lock);
2521                 return -1;
2522         }
2523
2524         ast_mutex_unlock(&p->lock);
2525
2526         return 0;
2527 }
2528
2529 static int pri_is_up(struct zt_pri *pri)
2530 {
2531         int x;
2532         for (x = 0; x < NUM_DCHANS; x++) {
2533                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2534                         return 1;
2535         }
2536         return 0;
2537 }
2538
2539 static int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2540 {
2541         bearer->owner = &inuse;
2542         bearer->realcall = crv;
2543         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2544         if (crv->subs[SUB_REAL].owner)
2545                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2546         crv->bearer = bearer;
2547         crv->call = bearer->call;
2548         crv->pri = pri;
2549         return 0;
2550 }
2551
2552 static char *pri_order(int level)
2553 {
2554         switch (level) {
2555         case 0:
2556                 return "Primary";
2557         case 1:
2558                 return "Secondary";
2559         case 2:
2560                 return "Tertiary";
2561         case 3:
2562                 return "Quaternary";
2563         default:
2564                 return "<Unknown>";
2565         }               
2566 }
2567
2568 /* Returns fd of the active dchan */
2569 static int pri_active_dchan_fd(struct zt_pri *pri)
2570 {
2571         int x = -1;
2572
2573         for (x = 0; x < NUM_DCHANS; x++) {
2574                 if ((pri->dchans[x] == pri->pri))
2575                         break;
2576         }
2577
2578         return pri->fds[x];
2579 }
2580
2581 static int pri_find_dchan(struct zt_pri *pri)
2582 {
2583         int oldslot = -1;
2584         struct pri *old;
2585         int newslot = -1;
2586         int x;
2587         old = pri->pri;
2588         for (x = 0; x < NUM_DCHANS; x++) {
2589                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2590                         newslot = x;
2591                 if (pri->dchans[x] == old) {
2592                         oldslot = x;
2593                 }
2594         }
2595         if (newslot < 0) {
2596                 newslot = 0;
2597                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2598                         pri->dchannels[newslot]);
2599         }
2600         if (old && (oldslot != newslot))
2601                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2602                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2603         pri->pri = pri->dchans[newslot];
2604         return 0;
2605 }
2606 #endif
2607
2608 static int zt_hangup(struct ast_channel *ast)
2609 {
2610         int res;
2611         int index,x, law;
2612         /*static int restore_gains(struct zt_pvt *p);*/
2613         struct zt_pvt *p = ast->tech_pvt;
2614         struct zt_pvt *tmp = NULL;
2615         struct zt_pvt *prev = NULL;
2616         ZT_PARAMS par;
2617
2618         if (option_debug)
2619                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2620         if (!ast->tech_pvt) {
2621                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2622                 return 0;
2623         }
2624         
2625         ast_mutex_lock(&p->lock);
2626         
2627         index = zt_get_index(ast, p, 1);
2628
2629         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
2630                 x = 1;
2631                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2632         }
2633
2634         x = 0;
2635         zt_confmute(p, 0);
2636         restore_gains(p);
2637         if (p->origcid_num) {
2638                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2639                 free(p->origcid_num);
2640                 p->origcid_num = NULL;
2641         }       
2642         if (p->origcid_name) {
2643                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2644                 free(p->origcid_name);
2645                 p->origcid_name = NULL;
2646         }       
2647         if (p->dsp)
2648                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2649         if (p->exten)
2650                 p->exten[0] = '\0';
2651
2652         if (option_debug)
2653                 ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2654                         p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2655         p->ignoredtmf = 0;
2656         
2657         if (index > -1) {
2658                 /* Real channel, do some fixup */
2659                 p->subs[index].owner = NULL;
2660                 p->subs[index].needanswer = 0;
2661                 p->subs[index].needflash = 0;
2662                 p->subs[index].needringing = 0;
2663                 p->subs[index].needbusy = 0;
2664                 p->subs[index].needcongestion = 0;
2665                 p->subs[index].linear = 0;
2666                 p->subs[index].needcallerid = 0;
2667                 p->polarity = POLARITY_IDLE;
2668                 zt_setlinear(p->subs[index].zfd, 0);
2669                 if (index == SUB_REAL) {
2670                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2671                                 if (option_debug)
2672                                         ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2673                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2674                                         /* We had flipped over to answer a callwait and now it's gone */
2675                                         if (option_debug)
2676                                                 ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2677                                         /* Move to the call-wait, but un-own us until they flip back. */
2678                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2679                                         unalloc_sub(p, SUB_CALLWAIT);
2680                                         p->owner = NULL;
2681                                 } else {
2682                                         /* The three way hung up, but we still have a call wait */
2683                                         if (option_debug)
2684                                                 ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2685                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2686                                         unalloc_sub(p, SUB_THREEWAY);
2687                                         if (p->subs[SUB_REAL].inthreeway) {
2688                                                 /* This was part of a three way call.  Immediately make way for
2689                                                    another call */
2690                                                 if (option_debug)
2691                                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2692                                                 p->owner = p->subs[SUB_REAL].owner;
2693                                         } else {
2694                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2695                                                 if (option_debug)
2696                                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2697                                                 p->owner = NULL;
2698                                         }
2699                                         p->subs[SUB_REAL].inthreeway = 0;
2700                                 }
2701                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2702                                 /* Move to the call-wait and switch back to them. */
2703                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2704                                 unalloc_sub(p, SUB_CALLWAIT);
2705                                 p->owner = p->subs[SUB_REAL].owner;
2706                                 if (p->owner->_state != AST_STATE_UP)
2707                                         p->subs[SUB_REAL].needanswer = 1;
2708                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2709                                         ast_queue_control(p->subs[SUB_REAL].owner, AST_CONTROL_UNHOLD);
2710                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2711                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2712                                 unalloc_sub(p, SUB_THREEWAY);
2713                                 if (p->subs[SUB_REAL].inthreeway) {
2714                                         /* This was part of a three way call.  Immediately make way for
2715                                            another call */
2716                                         if (option_debug)
2717                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2718                                         p->owner = p->subs[SUB_REAL].owner;
2719                                 } else {
2720                                         /* This call hasn't been completed yet...  Set owner to NULL */
2721                                         if (option_debug)
2722                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2723                                         p->owner = NULL;
2724                                 }
2725                                 p->subs[SUB_REAL].inthreeway = 0;
2726                         }
2727                 } else if (index == SUB_CALLWAIT) {
2728                         /* Ditch the holding callwait call, and immediately make it availabe */
2729                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2730                                 /* This is actually part of a three way, placed on hold.  Place the third part
2731                                    on music on hold now */
2732                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
2733                                         ast_queue_control_data(p->subs[SUB_THREEWAY].owner, AST_CONTROL_HOLD, 
2734                                                 S_OR(p->mohsuggest, NULL),
2735                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2736                                 }
2737                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2738                                 /* Make it the call wait now */
2739                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2740                                 unalloc_sub(p, SUB_THREEWAY);
2741                         } else
2742                                 unalloc_sub(p, SUB_CALLWAIT);
2743                 } else if (index == SUB_THREEWAY) {
2744                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2745                                 /* The other party of the three way call is currently in a call-wait state.
2746                                    Start music on hold for them, and take the main guy out of the third call */
2747                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner)) {
2748                                         ast_queue_control_data(p->subs[SUB_CALLWAIT].owner, AST_CONTROL_HOLD, 
2749                                                 S_OR(p->mohsuggest, NULL),
2750                                                 !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
2751                                 }
2752                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2753                         }
2754                         p->subs[SUB_REAL].inthreeway = 0;
2755                         /* If this was part of a three way call index, let us make
2756                            another three way call */
2757                         unalloc_sub(p, SUB_THREEWAY);
2758                 } else {
2759                         /* This wasn't any sort of call, but how are we an index? */
2760                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2761                 }
2762         }
2763
2764         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2765                 p->owner = NULL;
2766                 p->ringt = 0;
2767                 p->distinctivering = 0;
2768                 p->confirmanswer = 0;
2769                 p->cidrings = 1;
2770                 p->outgoing = 0;
2771                 p->digital = 0;
2772                 p->faxhandled = 0;
2773                 p->pulsedial = 0;
2774                 p->onhooktime = time(NULL);
2775 #ifdef HAVE_PRI
2776                 p->proceeding = 0;
2777                 p->progress = 0;
2778                 p->alerting = 0;
2779                 p->setup_ack = 0;
2780 #endif          
2781                 if (p->dsp) {
2782                         ast_dsp_free(p->dsp);
2783                         p->dsp = NULL;
2784                 }
2785
2786                 law = ZT_LAW_DEFAULT;
2787                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2788                 if (res < 0) 
2789                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2790                 /* Perform low level hangup if no owner left */
2791 #ifdef HAVE_SS7
2792                 if (p->ss7) {
2793                         if (p->ss7call) {
2794                                 if (!ss7_grab(p, p->ss7)) {
2795                                         if (!p->alreadyhungup) {
2796                                                 const char *cause = pbx_builtin_getvar_helper(ast,"SS7_CAUSE");
2797                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2798
2799                                                 if (cause) {
2800                                                         if (atoi(cause))
2801                                                                 icause = atoi(cause);
2802                                                 }
2803                                                 isup_rel(p->ss7->ss7, p->ss7call, icause);
2804                                                 ss7_rel(p->ss7);
2805                                                 p->alreadyhungup = 1;
2806                                         } else
2807                                                 ast_log(LOG_WARNING, "Trying to hangup twice!\n");
2808                                 } else {
2809                                         ast_log(LOG_WARNING, "Unable to grab SS7 on CIC %d\n", p->cic);
2810                                         res = -1;
2811                                 }
2812                         }
2813                 }
2814 #endif
2815 #ifdef HAVE_PRI
2816                 if (p->pri) {
2817 #ifdef SUPPORT_USERUSER
2818                         const char *useruser = pbx_builtin_getvar_helper(ast,"USERUSERINFO");
2819 #endif
2820
2821                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2822                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2823                                 if (!pri_grab(p, p->pri)) {
2824                                         if (p->alreadyhungup) {
2825                                                 if (option_debug)
2826                                                         ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2827
2828 #ifdef SUPPORT_USERUSER
2829                                                 pri_call_set_useruser(p->call, useruser);
2830 #endif
2831
2832                                                 pri_hangup(p->pri->pri, p->call, -1);
2833                                                 p->call = NULL;
2834                                                 if (p->bearer) 
2835                                                         p->bearer->call = NULL;
2836                                         } else {
2837                                                 const char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2838                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2839                                                 if (option_debug)
2840                                                         ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2841
2842 #ifdef SUPPORT_USERUSER
2843                                                 pri_call_set_useruser(p->call, useruser);
2844 #endif
2845
2846                                                 p->alreadyhungup = 1;
2847                                                 if (p->bearer)
2848                                                         p->bearer->alreadyhungup = 1;
2849                                                 if (cause) {
2850                                                         if (atoi(cause))
2851                                                                 icause = atoi(cause);
2852                                                 }
2853                                                 pri_hangup(p->pri->pri, p->call, icause);
2854                                         }
2855                                         if (res < 0) 
2856                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2857                                         pri_rel(p->pri);                        
2858                                 } else {
2859                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2860                                         res = -1;
2861                                 }
2862                         } else {
2863                                 if (p->bearer)
2864                                         if (option_debug)
2865                                                 ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2866                                 p->call = NULL;
2867                                 res = 0;
2868                         }
2869                 }
2870 #endif
2871                 if (p->sig && ((p->sig != SIG_PRI) && (p->sig != SIG_SS7)))
2872                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2873                 if (res < 0) {
2874                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2875                 }
2876                 switch (p->sig) {
2877                 case SIG_FXOGS:
2878                 case SIG_FXOLS:
2879                 case SIG_FXOKS:
2880                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2881                         if (!res) {
2882 #if 0
2883                                 if (option_debug)
2884                                         ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2885 #endif
2886                                 /* If they're off hook, try playing congestion */
2887                                 if ((par.rxisoffhook) && (!(p->radio || (p->oprmode < 0))))
2888                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2889                                 else
2890                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2891                         }
2892                         break;
2893                 case SIG_FXSGS:
2894                 case SIG_FXSLS:
2895                 case SIG_FXSKS:
2896                         /* Make sure we're not made available for at least two seconds assuming
2897                            we were actually used for an inbound or outbound call. */
2898                         if (ast->_state != AST_STATE_RESERVED) {
2899                                 time(&p->guardtime);
2900                                 p->guardtime += 2;
2901                         }
2902                         break;
2903                 default:
2904                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2905                 }
2906                 if (p->cidspill)
2907                         free(p->cidspill);
2908                 if (p->sig)
2909                         zt_disable_ec(p);
2910                 x = 0;
2911                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2912                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2913                 p->didtdd = 0;
2914                 p->cidspill = NULL;
2915                 p->callwaitcas = 0;
2916                 p->callwaiting = p->permcallwaiting;
2917                 p->hidecallerid = p->permhidecallerid;
2918                 p->dialing = 0;
2919                 p->rdnis[0] = '\0';
2920                 update_conf(p);
2921                 reset_conf(p);
2922                 /* Restore data mode */
2923                 if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
2924                         x = 0;
2925                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2926                 }
2927 #ifdef HAVE_PRI
2928                 if (p->bearer) {
2929                         if (option_debug)
2930                                 ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2931                         /* Free up the bearer channel as well, and
2932                            don't use its file descriptor anymore */
2933                         update_conf(p->bearer);
2934                         reset_conf(p->bearer);
2935                         p->bearer->owner = NULL;
2936                         p->bearer->realcall = NULL;
2937                         p->bearer = NULL;
2938                         p->subs[SUB_REAL].zfd = -1;
2939                         p->pri = NULL;
2940                 }
2941 #endif
2942                 restart_monitor();
2943         }
2944
2945         p->callwaitingrepeat = 0;
2946         p->cidcwexpire = 0;
2947         p->oprmode = 0;
2948         ast->tech_pvt = NULL;
2949         ast_mutex_unlock(&p->lock);
2950         ast_module_unref(ast_module_info->self);
2951         if (option_verbose > 2) 
2952                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2953
2954         ast_mutex_lock(&iflock);
2955         tmp = iflist;
2956         prev = NULL;
2957         if (p->destroy) {
2958                 while (tmp) {
2959                         if (tmp == p) {
2960                                 destroy_channel(prev, tmp, 0);
2961                                 break;
2962                         } else {
2963                                 prev = tmp;
2964                                 tmp = tmp->next;
2965                         }
2966                 }
2967         }
2968         ast_mutex_unlock(&iflock);
2969         return 0;
2970 }
2971
2972 static int zt_answer(struct ast_channel *ast)
2973 {
2974         struct zt_pvt *p = ast->tech_pvt;
2975         int res = 0;
2976         int index;
2977         int oldstate = ast->_state;
2978         ast_setstate(ast, AST_STATE_UP);
2979         ast_mutex_lock(&p->lock);
2980         index = zt_get_index(ast, p, 0);
2981         if (index < 0)
2982                 index = SUB_REAL;
2983         /* nothing to do if a radio channel */
2984         if ((p->radio || (p->oprmode < 0))) {
2985                 ast_mutex_unlock(&p->lock);
2986                 return 0;
2987         }
2988         switch (p->sig) {
2989         case SIG_FXSLS:
2990         case SIG_FXSGS:
2991         case SIG_FXSKS:
2992                 p->ringt = 0;
2993                 /* Fall through */
2994         case SIG_EM:
2995         case SIG_EM_E1:
2996         case SIG_EMWINK:
2997         case SIG_FEATD:
2998         case SIG_FEATDMF:
2999         case SIG_FEATDMF_TA:
3000         case SIG_E911:
3001         case SIG_FGC_CAMA:
3002         case SIG_FGC_CAMAMF:
3003         case SIG_FEATB:
3004         case SIG_SF:
3005         case SIG_SFWINK:
3006         case SIG_SF_FEATD:
3007         case SIG_SF_FEATDMF:
3008         case SIG_SF_FEATB:
3009         case SIG_FXOLS:
3010         case SIG_FXOGS:
3011         case SIG_FXOKS:
3012                 /* Pick up the line */
3013                 if (option_debug)
3014                         ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
3015                 if (p->hanguponpolarityswitch) {
3016                         gettimeofday(&p->polaritydelaytv, NULL);
3017                 }
3018                 res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
3019                 tone_zone_play_tone(p->subs[index].zfd, -1);
3020                 p->dialing = 0;
3021                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
3022                         if (oldstate == AST_STATE_RINGING) {
3023                                 if (option_debug)
3024                                         ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
3025                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
3026                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3027                                 p->owner = p->subs[SUB_REAL].owner;
3028                         }
3029                 }
3030                 if (p->sig & __ZT_SIG_FXS) {
3031                         zt_enable_ec(p);
3032                         zt_train_ec(p);
3033                 }
3034                 break;
3035 #ifdef HAVE_PRI
3036         case SIG_PRI:
3037                 /* Send a pri acknowledge */
3038                 if (!pri_grab(p, p->pri)) {
3039                         p->proceeding = 1;
3040                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
3041                         pri_rel(p->pri);
3042                 } else {
3043                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
3044                         res = -1;
3045                 }
3046                 break;
3047 #endif
3048 #ifdef HAVE_SS7
3049         case SIG_SS7:
3050                 if (!ss7_grab(p, p->ss7)) {
3051                         p->proceeding = 1;
3052                         res = isup_anm(p->ss7->ss7, p->ss7call);
3053                         ss7_rel(p->ss7);
3054                 } else {
3055                         ast_log(LOG_WARNING, "Unable to grab SS7 on span %d\n", p->span);
3056                         res = -1;
3057                 }
3058                 break;
3059 #endif
3060         case 0:
3061                 ast_mutex_unlock(&p->lock);
3062                 return 0;
3063         default:
3064                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
3065                 res = -1;
3066         }
3067         ast_mutex_unlock(&p->lock);
3068         return res;
3069 }
3070
3071 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
3072 {
3073         char *cp;
3074         signed char *scp;
3075         int x;
3076         int index;
3077         struct zt_pvt *p = chan->tech_pvt, *pp;
3078         struct oprmode *oprmode;
3079         
3080
3081         /* all supported options require data */
3082         if (!data || (datalen < 1)) {
3083                 errno = EINVAL;
3084                 return -1;
3085         }
3086
3087         switch (option) {
3088         case AST_OPTION_TXGAIN:
3089                 scp = (signed char *) data;
3090                 index = zt_get_index(chan, p, 0);
3091                 if (index < 0) {
3092                         ast_log(LOG_WARNING, "No index in TXGAIN?\n");
3093                         return -1;
3094                 }
3095                 if (option_debug)
3096                         ast_log(LOG_DEBUG, "Setting actual tx gain on %s to %f\n", chan->name, p->txgain + (float) *scp);
3097                 return set_actual_txgain(p->subs[index].zfd, 0, p->txgain + (float) *scp, p->law);
3098         case AST_OPTION_RXGAIN:
3099                 scp = (signed char *) data;
3100                 index = zt_get_index(chan, p, 0);
3101                 if (index < 0) {
3102                         ast_log(LOG_WARNING, "No index in RXGAIN?\n");
3103                         return -1;
3104                 }
3105                 if (option_debug)
3106                         ast_log(LOG_DEBUG, "Setting actual rx gain on %s to %f\n", chan->name, p->rxgain + (float) *scp);
3107                 return set_actual_rxgain(p->subs[index].zfd, 0, p->rxgain + (float) *scp, p->law);
3108         case AST_OPTION_TONE_VERIFY:
3109                 if (!p->dsp)
3110                         break;
3111                 cp = (char *) data;
3112                 switch (*cp) {
3113                 case 1:
3114                         if (option_debug)
3115                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
3116                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
3117                         break;
3118                 case 2:
3119                         if (option_debug)
3120                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
3121                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
3122                         break;
3123                 default:
3124                         if (option_debug)
3125                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
3126                         ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
3127                         break;
3128                 }
3129                 break;
3130         case AST_OPTION_TDD:
3131                 /* turn on or off TDD */
3132                 cp = (char *) data;
3133                 p->mate = 0;
3134                 if (!*cp) { /* turn it off */
3135                         if (option_debug)
3136                                 ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
3137                         if (p->tdd)
3138                                 tdd_free(p->tdd);
3139                         p->tdd = 0;
3140                         break;
3141                 }
3142                 if (option_debug)
3143                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: %s(%d) on %s\n",
3144                                 (*cp == 2) ? "MATE" : "ON", (int) *cp, chan->name);
3145                 zt_disable_ec(p);
3146                 /* otherwise, turn it on */
3147                 if (!p->didtdd) { /* if havent done it yet */
3148                         unsigned char mybuf[41000], *buf;
3149                         int size, res, fd, len;
3150                         struct pollfd fds[1];
3151
3152                         buf = mybuf;
3153                         memset(buf, 0x7f, sizeof(mybuf)); /* set to silence */
3154                         ast_tdd_gen_ecdisa(buf + 16000, 16000);  /* put in tone */
3155                         len = 40000;
3156                         index = zt_get_index(chan, p, 0);
3157                         if (index < 0) {
3158                                 ast_log(LOG_WARNING, "No index in TDD?\n");
3159                                 return -1;
3160                         }
3161                         fd = p->subs[index].zfd;
3162                         while (len) {
3163                                 if (ast_check_hangup(chan))
3164                                         return -1;
3165                                 size = len;
3166                                 if (size > READ_SIZE)
3167                                         size = READ_SIZE;
3168                                 fds[0].fd = fd;
3169                                 fds[0].events = POLLPRI | POLLOUT;
3170                                 fds[0].revents = 0;
3171                                 res = poll(fds, 1, -1);
3172                                 if (!res) {
3173                                         if (option_debug)
3174                                                 ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
3175                                         continue;
3176                                 }
3177                                 /* if got exception */
3178                                 if (fds[0].revents & POLLPRI)
3179                                         return -1;
3180                                 if (!(fds[0].revents & POLLOUT)) {
3181                                         if (option_debug)
3182                                                 ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
3183                                         continue;
3184                                 }
3185                                 res = write(fd, buf, size);
3186                                 if (res != size) {
3187                                         if (res == -1) return -1;
3188                                         if (option_debug)
3189                                                 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
3190                                         break;
3191                                 }
3192                                 len -= size;
3193                                 buf += size;
3194                         }
3195                         p->didtdd = 1; /* set to have done it now */            
3196                 }
3197                 if (*cp == 2) { /* Mate mode */
3198                         if (p->tdd)
3199                                 tdd_free(p->tdd);
3200                         p->tdd = 0;
3201                         p->mate = 1;
3202                         break;
3203                 }               
3204                 if (!p->tdd) { /* if we dont have one yet */
3205                         p->tdd = tdd_new(); /* allocate one */
3206                 }               
3207                 break;
3208         case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
3209                 if (!p->dsp)
3210                         break;
3211                 cp = (char *) data;
3212                 if (option_debug)
3213                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: %s(%d) on %s\n",
3214                                 *cp ? "ON" : "OFF", (int) *cp, chan->name);
3215                 ast_dsp_digitmode(p->dsp, ((*cp) ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF) | p->dtmfrelax);
3216                 break;
3217         case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
3218                 cp = (char *) data;
3219                 if (!*cp) {             
3220                         if (option_debug)
3221                                 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n", chan->name);
3222                         x = 0;
3223                         zt_disable_ec(p);
3224                 } else {                
3225                         if (option_debug)
3226                                 ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n", chan->name);
3227                         x = 1;
3228                 }
3229                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
3230                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
3231                 break;
3232         case AST_OPTION_OPRMODE:  /* Operator services mode */
3233                 oprmode = (struct oprmode *) data;
3234                 pp = oprmode->peer->tech_pvt;
3235                 p->oprmode = pp->oprmode = 0;
3236                 /* setup peers */
3237                 p->oprpeer = pp;
3238                 pp->oprpeer = p;
3239                 /* setup modes, if any */
3240                 if (oprmode->mode) 
3241                 {
3242                         pp->oprmode = oprmode->mode;
3243                         p->oprmode = -oprmode->mode;
3244                 }
3245                 if (option_debug)
3246                         ast_log(LOG_DEBUG, "Set Operator Services mode, value: %d on %s/%s\n",
3247                                 oprmode->mode, chan->name,oprmode->peer->name);
3248                 break;
3249         case AST_OPTION_ECHOCAN:
3250                 cp = (char *) data;
3251                 if (*cp) {
3252                         if (option_debug)
3253                                 ast_log(LOG_DEBUG, "Enabling echo cancelation on %s\n", chan->name);
3254                         zt_enable_ec(p);
3255                 } else {
3256                         if (option_debug)
3257                                 ast_log(LOG_DEBUG, "Disabling echo cancelation on %s\n", chan->name);
3258                         zt_disable_ec(p);
3259                 }
3260                 break;
3261         }
3262         errno = 0;
3263
3264         return 0;
3265 }
3266
3267 static int zt_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len)
3268 {
3269         struct zt_pvt *p = chan->tech_pvt;
3270         
3271         if (!strcasecmp(data, "rxgain")) {
3272                 ast_mutex_lock(&p->lock);
3273                 snprintf(buf, len, "%f", p->rxgain);
3274                 ast_mutex_unlock(&p->lock);     
3275         } else if (!strcasecmp(data, "txgain")) {
3276                 ast_mutex_lock(&p->lock);
3277                 snprintf(buf, len, "%f", p->txgain);
3278                 ast_mutex_unlock(&p->lock);     
3279         } else {
3280                 ast_copy_string(buf, "", len);
3281         }
3282         return 0;
3283 }
3284
3285
3286 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
3287 {
3288         /* Unlink a specific slave or all slaves/masters from a given master */
3289         int x;
3290         int hasslaves;
3291         if (!master)
3292                 return;
3293         if (needlock) {
3294                 ast_mutex_lock(&master->lock);
3295                 if (slave) {
3296                         while (ast_mutex_trylock(&slave->lock)) {
3297                                 ast_mutex_unlock(&master->lock);
3298                                 usleep(1);
3299                                 ast_mutex_lock(&master->lock);
3300                         }
3301                 }
3302         }
3303         hasslaves = 0;
3304         for (x = 0; x < MAX_SLAVES; x++) {
3305                 if (master->slaves[x]) {
3306                         if (!slave || (master->slaves[x] == slave)) {
3307                                 /* Take slave out of the conference */
3308                                 if (option_debug)
3309                                         ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
3310                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
3311                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
3312                                 master->slaves[x]->master = NULL;
3313                                 master->slaves[x] = NULL;
3314                         } else
3315                                 hasslaves = 1;
3316                 }
3317                 if (!hasslaves)
3318                         master->inconference = 0;
3319         }
3320         if (!slave) {
3321                 if (master->master) {
3322                         /* Take master out of the conference */
3323                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
3324                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
3325                         hasslaves = 0;
3326                         for (x = 0; x < MAX_SLAVES; x++) {
3327                                 if (master->master->slaves[x] == master)
3328                                         master->master->slaves[x] = NULL;
3329                                 else if (master->master->slaves[x])
3330                                         hasslaves = 1;
3331                         }
3332                         if (!hasslaves)
3333                                 master->master->inconference = 0;
3334                 }
3335                 master->master = NULL;
3336         }
3337         update_conf(master);
3338         if (needlock) {
3339                 if (slave)
3340                         ast_mutex_unlock(&slave->lock);
3341                 ast_mutex_unlock(&master->lock);
3342         }
3343 }
3344
3345 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
3346         int x;
3347         if (!slave || !master) {
3348                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
3349                 return;
3350         }
3351         for (x = 0; x < MAX_SLAVES; x++) {
3352                 if (!master->slaves[x]) {
3353                         master->slaves[x] = slave;
3354                         break;
3355                 }
3356         }
3357         if (x >= MAX_SLAVES) {
3358                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
3359                 master->slaves[MAX_SLAVES - 1] = slave;
3360         }
3361         if (slave->master) 
3362                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
3363         slave->master = master;
3364         
3365         if (option_debug)
3366                 ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
3367 }
3368
3369 static void disable_dtmf_detect(struct zt_pvt *p)
3370 {
3371 #ifdef ZT_TONEDETECT
3372         int val;
3373 #endif
3374
3375         p->ignoredtmf = 1;
3376
3377 #ifdef ZT_TONEDETECT
3378         val = 0;
3379         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3380 #endif          
3381         if (!p->hardwaredtmf && p->dsp) {
3382                 p->dsp_features &= ~DSP_FEATURE_DTMF_DETECT;
3383                 ast_dsp_set_features(p->dsp, p->dsp_features);
3384         }
3385 }
3386
3387 static void enable_dtmf_detect(struct zt_pvt *p)
3388 {
3389 #ifdef ZT_TONEDETECT
3390         int val;
3391 #endif
3392
3393         if (p->channel == CHAN_PSEUDO)
3394                 return;
3395
3396         p->ignoredtmf = 0;
3397
3398 #ifdef ZT_TONEDETECT
3399         val = ZT_TONEDETECT_ON | ZT_TONEDETECT_MUTE;
3400         ioctl(p->subs[SUB_REAL].zfd, ZT_TONEDETECT, &val);
3401 #endif          
3402         if (!p->hardwaredtmf && p->dsp) {
3403                 p->dsp_features |= DSP_FEATURE_DTMF_DETECT;
3404                 ast_dsp_set_features(p->dsp, p->dsp_features);
3405         }
3406 }
3407
3408 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)
3409 {
3410         struct ast_channel *who;
3411         struct zt_pvt *p0, *p1, *op0, *op1;
3412         struct zt_pvt *master = NULL, *slave = NULL;
3413         struct ast_frame *f;
3414         int inconf = 0;
3415         int nothingok = 1;
3416         int ofd0, ofd1;
3417         int oi0, oi1, i0 = -1, i1 = -1, t0, t1;
3418         int os0 = -1, os1 = -1;
3419         int priority = 0;
3420         struct ast_channel *oc0, *oc1;
3421         enum ast_bridge_result res;
3422
3423 #ifdef PRI_2BCT
3424         int triedtopribridge = 0;
3425         q931_call *q931c0 = NULL, *q931c1 = NULL;
3426 #endif
3427
3428         /* For now, don't attempt to native bridge if either channel needs DTMF detection.