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