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