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