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