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