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