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