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