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