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