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