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