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