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