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