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