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