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