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