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