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