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