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