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