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