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