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