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