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