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