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