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