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