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