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