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