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