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