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