updates from angler
[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 *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 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1115 {
1116         /* If the conference already exists, and we're already in it
1117            don't bother doing anything */
1118         ZT_CONFINFO zi;
1119         
1120         memset(&zi, 0, sizeof(zi));
1121         zi.chan = 0;
1122
1123         if (slavechannel > 0) {
1124                 /* If we have only one slave, do a digital mon */
1125                 zi.confmode = ZT_CONF_DIGITALMON;
1126                 zi.confno = slavechannel;
1127         } else {
1128                 if (!index) {
1129                         /* Real-side and pseudo-side both participate in conference */
1130                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1131                                                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1132                 } else
1133                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1134                 zi.confno = p->confno;
1135         }
1136         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1137                 return 0;
1138         if (c->zfd < 0)
1139                 return 0;
1140         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1141                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1142                 return -1;
1143         }
1144         if (slavechannel < 1) {
1145                 p->confno = zi.confno;
1146         }
1147         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1148         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1149         return 0;
1150 }
1151
1152 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1153 {
1154         /* If they're listening to our channel, they're ours */ 
1155         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1156                 return 1;
1157         /* If they're a talker on our (allocated) conference, they're ours */
1158         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1159                 return 1;
1160         return 0;
1161 }
1162
1163 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1164 {
1165         ZT_CONFINFO zi;
1166         if (/* Can't delete if there's no zfd */
1167                 (c->zfd < 0) ||
1168                 /* Don't delete from the conference if it's not our conference */
1169                 !isourconf(p, c)
1170                 /* Don't delete if we don't think it's conferenced at all (implied) */
1171                 ) return 0;
1172         memset(&zi, 0, sizeof(zi));
1173         zi.chan = 0;
1174         zi.confno = 0;
1175         zi.confmode = 0;
1176         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1177                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1178                 return -1;
1179         }
1180         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1181         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1182         return 0;
1183 }
1184
1185 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1186 {
1187         int x;
1188         int useslavenative;
1189         struct zt_pvt *slave = NULL;
1190         /* Start out optimistic */
1191         useslavenative = 1;
1192         /* Update conference state in a stateless fashion */
1193         for (x=0;x<3;x++) {
1194                 /* Any three-way calling makes slave native mode *definitely* out
1195                    of the question */
1196                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1197                         useslavenative = 0;
1198         }
1199         /* If we don't have any 3-way calls, check to see if we have
1200            precisely one slave */
1201         if (useslavenative) {
1202                 for (x=0;x<MAX_SLAVES;x++) {
1203                         if (p->slaves[x]) {
1204                                 if (slave) {
1205                                         /* Whoops already have a slave!  No 
1206                                            slave native and stop right away */
1207                                         slave = NULL;
1208                                         useslavenative = 0;
1209                                         break;
1210                                 } else {
1211                                         /* We have one slave so far */
1212                                         slave = p->slaves[x];
1213                                 }
1214                         }
1215                 }
1216         }
1217         /* If no slave, slave native definitely out */
1218         if (!slave)
1219                 useslavenative = 0;
1220         else if (slave->law != p->law) {
1221                 useslavenative = 0;
1222                 slave = NULL;
1223         }
1224         if (out)
1225                 *out = slave;
1226         return useslavenative;
1227 }
1228
1229 static int reset_conf(struct zt_pvt *p)
1230 {
1231         ZT_CONFINFO zi;
1232         memset(&zi, 0, sizeof(zi));
1233         p->confno = -1;
1234         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1235         if (p->subs[SUB_REAL].zfd > -1) {
1236                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1237                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1238         }
1239         return 0;
1240 }
1241
1242 static int update_conf(struct zt_pvt *p)
1243 {
1244         int needconf = 0;
1245         int x;
1246         int useslavenative;
1247         struct zt_pvt *slave = NULL;
1248
1249         useslavenative = isslavenative(p, &slave);
1250         /* Start with the obvious, general stuff */
1251         for (x=0;x<3;x++) {
1252                 /* Look for three way calls */
1253                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1254                         conf_add(p, &p->subs[x], x, 0);
1255                         needconf++;
1256                 } else {
1257                         conf_del(p, &p->subs[x], x);
1258                 }
1259         }
1260         /* If we have a slave, add him to our conference now. or DAX
1261            if this is slave native */
1262         for (x=0;x<MAX_SLAVES;x++) {
1263                 if (p->slaves[x]) {
1264                         if (useslavenative)
1265                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1266                         else {
1267                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1268                                 needconf++;
1269                         }
1270                 }
1271         }
1272         /* If we're supposed to be in there, do so now */
1273         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1274                 if (useslavenative)
1275                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1276                 else {
1277                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1278                         needconf++;
1279                 }
1280         }
1281         /* If we have a master, add ourselves to his conference */
1282         if (p->master) {
1283                 if (isslavenative(p->master, NULL)) {
1284                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1285                 } else {
1286                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1287                 }
1288         }
1289         if (!needconf) {
1290                 /* Nobody is left (or should be left) in our conference.  
1291                    Kill it.  */
1292                 p->confno = -1;
1293         }
1294         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1295         return 0;
1296 }
1297
1298 static void zt_enable_ec(struct zt_pvt *p)
1299 {
1300         int x;
1301         int res;
1302         if (!p)
1303                 return;
1304         if (p->echocanon) {
1305                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1306                 return;
1307         }
1308         if (p->digital) {
1309                 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1310                 return;
1311         }
1312         if (p->echocancel) {
1313                 if (p->sig == SIG_PRI) {
1314                         x = 1;
1315                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1316                         if (res)
1317                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1318                 }
1319                 x = p->echocancel;
1320                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1321                 if (res) 
1322                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1323                 else {
1324                         p->echocanon = 1;
1325                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1326                 }
1327         } else
1328                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1329 }
1330
1331 static void zt_train_ec(struct zt_pvt *p)
1332 {
1333         int x;
1334         int res;
1335         if (p && p->echocancel && p->echotraining) {
1336                 x = p->echotraining;
1337                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1338                 if (res) 
1339                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1340                 else {
1341                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1342                 }
1343         } else
1344                 ast_log(LOG_DEBUG, "No echo training requested\n");
1345 }
1346
1347 static void zt_disable_ec(struct zt_pvt *p)
1348 {
1349         int x;
1350         int res;
1351         if (p->echocancel) {
1352                 x = 0;
1353                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1354                 if (res) 
1355                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1356                 else
1357                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1358         }
1359         p->echocanon = 0;
1360 }
1361
1362 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1363 {
1364         struct  zt_gains g;
1365         float ltxgain;
1366         float lrxgain;
1367         int j,k;
1368         g.chan = chan;
1369         if ((rxgain != 0.0)  || (txgain != 0.0)) {
1370                 /* caluculate linear value of tx gain */
1371                 ltxgain = pow(10.0,txgain / 20.0);
1372                 /* caluculate linear value of rx gain */
1373                 lrxgain = pow(10.0,rxgain / 20.0);
1374                 if (law == ZT_LAW_ALAW) {
1375                         for (j=0;j<256;j++) {
1376                                 k = (int)(((float)AST_ALAW(j)) * lrxgain);
1377                                 if (k > 32767) k = 32767;
1378                                 if (k < -32767) k = -32767;
1379                                 g.rxgain[j] = AST_LIN2A(k);
1380                                 k = (int)(((float)AST_ALAW(j)) * ltxgain);
1381                                 if (k > 32767) k = 32767;
1382                                 if (k < -32767) k = -32767;
1383                                 g.txgain[j] = AST_LIN2A(k);
1384                         }
1385                 } else {
1386                         for (j=0;j<256;j++) {
1387                                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
1388                                 if (k > 32767) k = 32767;
1389                                 if (k < -32767) k = -32767;
1390                                 g.rxgain[j] = AST_LIN2MU(k);
1391                                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
1392                                 if (k > 32767) k = 32767;
1393                                 if (k < -32767) k = -32767;
1394                                 g.txgain[j] = AST_LIN2MU(k);
1395                         }
1396                 }
1397         } else {
1398                 for (j=0;j<256;j++) {
1399                         g.rxgain[j] = j;
1400                         g.txgain[j] = j;
1401                 }
1402         }
1403                 
1404           /* set 'em */
1405         return(ioctl(fd,ZT_SETGAINS,&g));
1406 }
1407
1408 static inline int zt_set_hook(int fd, int hs)
1409 {
1410         int x, res;
1411         x = hs;
1412         res = ioctl(fd, ZT_HOOK, &x);
1413         if (res < 0) 
1414         {
1415                 if (errno == EINPROGRESS) return 0;
1416                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1417         }
1418         return res;
1419 }
1420
1421 static inline int zt_confmute(struct zt_pvt *p, int muted)
1422 {
1423         int x, y, res;
1424         x = muted;
1425         if (p->sig == SIG_PRI) {
1426                 y = 1;
1427                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1428                 if (res)
1429                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1430         }
1431         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1432         if (res < 0) 
1433                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1434         return res;
1435 }
1436
1437 static int save_conference(struct zt_pvt *p)
1438 {
1439         struct zt_confinfo c;
1440         int res;
1441         if (p->saveconf.confmode) {
1442                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1443                 return -1;
1444         }
1445         p->saveconf.chan = 0;
1446         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1447         if (res) {
1448                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1449                 p->saveconf.confmode = 0;
1450                 return -1;
1451         }
1452         c.chan = 0;
1453         c.confno = 0;
1454         c.confmode = ZT_CONF_NORMAL;
1455         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1456         if (res) {
1457                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1458                 return -1;
1459         }
1460         if (option_debug)
1461                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1462         return 0;
1463 }
1464
1465 static int restore_conference(struct zt_pvt *p)
1466 {
1467         int res;
1468         if (p->saveconf.confmode) {
1469                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1470                 p->saveconf.confmode = 0;
1471                 if (res) {
1472                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1473                         return -1;
1474                 }
1475         }
1476         if (option_debug)
1477                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1478         return 0;
1479 }
1480
1481 static int send_callerid(struct zt_pvt *p);
1482
1483 int send_cwcidspill(struct zt_pvt *p)
1484 {
1485         p->callwaitcas = 0;
1486         p->cidcwexpire = 0;
1487         p->cidspill = malloc(MAX_CALLERID_SIZE);
1488         if (p->cidspill) {
1489                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
1490                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1491                 /* Make sure we account for the end */
1492                 p->cidlen += READ_SIZE * 4;
1493                 p->cidpos = 0;
1494                 send_callerid(p);
1495                 if (option_verbose > 2)
1496                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1497         } else return -1;
1498         return 0;
1499 }
1500
1501 static int has_voicemail(struct zt_pvt *p)
1502 {
1503
1504         return ast_app_has_voicemail(p->mailbox, NULL);
1505 }
1506
1507 static int send_callerid(struct zt_pvt *p)
1508 {
1509         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1510         int res;
1511         /* Take out of linear mode if necessary */
1512         if (p->subs[SUB_REAL].linear) {
1513                 p->subs[SUB_REAL].linear = 0;
1514                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1515         }
1516         while(p->cidpos < p->cidlen) {
1517                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1518                 if (res < 0) {
1519                         if (errno == EAGAIN)
1520                                 return 0;
1521                         else {
1522                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1523                                 return -1;
1524                         }
1525                 }
1526                 if (!res)
1527                         return 0;
1528                 p->cidpos += res;
1529         }
1530         free(p->cidspill);
1531         p->cidspill = NULL;
1532         if (p->callwaitcas) {
1533                 /* Wait for CID/CW to expire */
1534                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1535         } else
1536                 restore_conference(p);
1537         return 0;
1538 }
1539
1540 static int zt_callwait(struct ast_channel *ast)
1541 {
1542         struct zt_pvt *p = ast->tech_pvt;
1543         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1544         if (p->cidspill) {
1545                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1546                 free(p->cidspill);
1547         }
1548         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
1549         if (p->cidspill) {
1550                 save_conference(p);
1551                 /* Silence */
1552                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1553                 if (!p->callwaitrings && p->callwaitingcallerid) {
1554                         ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1555                         p->callwaitcas = 1;
1556                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
1557                 } else {
1558                         ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1559                         p->callwaitcas = 0;
1560                         p->cidlen = 2400 + READ_SIZE * 4;
1561                 }
1562                 p->cidpos = 0;
1563                 send_callerid(p);
1564         } else {
1565                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
1566                 return -1;
1567         }
1568         return 0;
1569 }
1570
1571 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1572 {
1573         struct zt_pvt *p = ast->tech_pvt;
1574         int x, res, index;
1575         char *c, *n, *l;
1576 #ifdef ZAPATA_PRI
1577         char *s=NULL;
1578 #endif
1579         char dest[256]; /* must be same length as p->dialdest */
1580         ast_mutex_lock(&p->lock);
1581         strncpy(dest, rdest, sizeof(dest) - 1);
1582         strncpy(p->dialdest, rdest, sizeof(dest) - 1);
1583         if ((ast->_state == AST_STATE_BUSY)) {
1584                 p->subs[SUB_REAL].needbusy = 1;
1585                 ast_mutex_unlock(&p->lock);
1586                 return 0;
1587         }
1588         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1589                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1590                 ast_mutex_unlock(&p->lock);
1591                 return -1;
1592         }
1593         p->dialednone = 0;
1594         if (p->radio)  /* if a radio channel, up immediately */
1595         {
1596                 /* Special pseudo -- automatically up */
1597                 ast_setstate(ast, AST_STATE_UP); 
1598                 ast_mutex_unlock(&p->lock);
1599                 return 0;
1600         }
1601         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1602         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1603         if (res)
1604                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1605         p->outgoing = 1;
1606
1607         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1608
1609         switch(p->sig) {
1610         case SIG_FXOLS:
1611         case SIG_FXOGS:
1612         case SIG_FXOKS:
1613                 if (p->owner == ast) {
1614                         /* Normal ring, on hook */
1615                         
1616                         /* Don't send audio while on hook, until the call is answered */
1617                         p->dialing = 1;
1618                         if (p->use_callerid) {
1619                                 /* Generate the Caller-ID spill if desired */
1620                                 if (p->cidspill) {
1621                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1622                                         free(p->cidspill);
1623                                 }
1624                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
1625                                 p->callwaitcas = 0;
1626                                 if (p->cidspill) {
1627                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1628                                         p->cidpos = 0;
1629                                         send_callerid(p);
1630                                 } else
1631                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
1632                         }
1633                         /* Choose proper cadence */
1634                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1635                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1636                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1637                                 p->cidrings = cidrings[p->distinctivering - 1];
1638                         } else {
1639                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1640                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1641                                 p->cidrings = p->sendcalleridafter;
1642                         }
1643
1644
1645                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1646                         c = strchr(dest, '/');
1647                         if (c)
1648                                 c++;
1649                         if (c && (strlen(c) < p->stripmsd)) {
1650                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1651                                 c = NULL;
1652                         }
1653                         if (c) {
1654                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1655                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1656                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1657                         } else {
1658                                 p->dop.dialstr[0] = '\0';
1659                         }
1660                         x = ZT_RING;
1661                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1662                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1663                                 ast_mutex_unlock(&p->lock);
1664                                 return -1;
1665                         }
1666                         p->dialing = 1;
1667                 } else {
1668                         /* Call waiting call */
1669                         p->callwaitrings = 0;
1670                         if (ast->cid.cid_num)
1671                                 strncpy(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num)-1);
1672                         else
1673                                 p->callwait_num[0] = '\0';
1674                         if (ast->cid.cid_name)
1675                                 strncpy(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name)-1);
1676                         else
1677                                 p->callwait_name[0] = '\0';
1678                         /* Call waiting tone instead */
1679                         if (zt_callwait(ast)) {
1680                                 ast_mutex_unlock(&p->lock);
1681                                 return -1;
1682                         }
1683                         /* Make ring-back */
1684                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1685                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1686                                 
1687                 }
1688                 n = ast->cid.cid_name;
1689                 l = ast->cid.cid_num;
1690                 if (l)
1691                         strncpy(p->lastcid_num, l, sizeof(p->lastcid_num) - 1);
1692                 else
1693                         p->lastcid_num[0] = '\0';
1694                 if (n)
1695                         strncpy(p->lastcid_name, n, sizeof(p->lastcid_name) - 1);
1696                 else
1697                         p->lastcid_name[0] = '\0';
1698                 ast_setstate(ast, AST_STATE_RINGING);
1699                 index = zt_get_index(ast, p, 0);
1700                 if (index > -1) {
1701                         p->subs[index].needringing = 1;
1702                 }
1703                 break;
1704         case SIG_FXSLS:
1705         case SIG_FXSGS:
1706         case SIG_FXSKS:
1707         case SIG_EMWINK:
1708         case SIG_EM:
1709         case SIG_EM_E1:
1710         case SIG_FEATD:
1711         case SIG_FEATDMF:
1712         case SIG_E911:
1713         case SIG_FEATB:
1714         case SIG_SFWINK:
1715         case SIG_SF:
1716         case SIG_SF_FEATD:
1717         case SIG_SF_FEATDMF:
1718         case SIG_SF_FEATB:
1719                 c = strchr(dest, '/');
1720                 if (c)
1721                         c++;
1722                 else
1723                         c = "";
1724                 if (strlen(c) < p->stripmsd) {
1725                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1726                         ast_mutex_unlock(&p->lock);
1727                         return -1;
1728                 }
1729 #ifdef ZAPATA_PRI
1730                 /* Start the trunk, if not GR-303 */
1731                 if (!p->pri) {
1732 #endif
1733                         x = ZT_START;
1734                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1735                         if (res < 0) {
1736                                 if (errno != EINPROGRESS) {
1737                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1738                                         ast_mutex_unlock(&p->lock);
1739                                         return -1;
1740                                 }
1741                         }
1742 #ifdef ZAPATA_PRI
1743                 }
1744 #endif
1745                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1746                 p->dop.op = ZT_DIAL_OP_REPLACE;
1747                 if (p->sig == SIG_FEATD) {
1748                         l = ast->cid.cid_num;
1749                         if (l) 
1750                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1751                         else
1752                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1753                 } else 
1754                 if (p->sig == SIG_FEATDMF) {
1755                         l = ast->cid.cid_num;
1756                         if (l) 
1757                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1758                         else
1759                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1760                 } else 
1761                 if (p->sig == SIG_E911) {
1762                         strncpy(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr) - 1);
1763                 } else
1764                 if (p->sig == SIG_FEATB) {
1765                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1766                 } else 
1767                 if(p->pulse)
1768                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c + p->stripmsd);
1769                 else
1770                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c + p->stripmsd);
1771                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1772                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1773                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1774                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1775                         p->echobreak = 1;
1776                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1777                 } else
1778                         p->echobreak = 0;
1779                 if (!res) {
1780                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1781                                 x = ZT_ONHOOK;
1782                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1783                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1784                                 ast_mutex_unlock(&p->lock);
1785                                 return -1;
1786                         }
1787                 } else
1788                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1789                 p->dialing = 1;
1790                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1791                 ast_setstate(ast, AST_STATE_DIALING);
1792                 break;
1793         case 0:
1794                 /* Special pseudo -- automatically up*/
1795                 ast_setstate(ast, AST_STATE_UP);
1796                 break;          
1797         case SIG_PRI:
1798                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1799                 p->dialdest[0] = '\0';
1800                 break;
1801         default:
1802                 ast_log(LOG_DEBUG, "not yet implemented\n");
1803                 ast_mutex_unlock(&p->lock);
1804                 return -1;
1805         }
1806 #ifdef ZAPATA_PRI
1807         if (p->pri) {
1808                 struct pri_sr *sr;
1809                 int pridialplan;
1810                 int dp_strip;
1811                 int prilocaldialplan;
1812                 int ldp_strip;
1813                 c = strchr(dest, '/');
1814                 if (c)
1815                         c++;
1816                 else
1817                         c = dest;
1818                 if (!p->hidecallerid) {
1819                         l = ast->cid.cid_num;
1820                         n = ast->cid.cid_name;
1821                 } else {
1822                         l = NULL;
1823                         n = NULL;
1824                 }
1825                 if (strlen(c) < p->stripmsd) {
1826                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1827                         ast_mutex_unlock(&p->lock);
1828                         return -1;
1829                 }
1830                 if (p->sig != SIG_FXSKS) {
1831                         p->dop.op = ZT_DIAL_OP_REPLACE;
1832                         s = strchr(c + p->stripmsd, 'w');
1833                         if (s) {
1834                                 if (strlen(s))
1835                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1836                                 else
1837                                         p->dop.dialstr[0] = '\0';
1838                                 *s = '\0';
1839                         } else {
1840                                 p->dop.dialstr[0] = '\0';
1841                         }
1842                 }
1843                 if (pri_grab(p, p->pri)) {
1844                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1845                         ast_mutex_unlock(&p->lock);
1846                         return -1;
1847                 }
1848                 if (!(p->call = pri_new_call(p->pri->pri))) {
1849                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1850                         pri_rel(p->pri);
1851                         ast_mutex_unlock(&p->lock);
1852                         return -1;
1853                 }
1854                 if (!(sr = pri_sr_new())) {
1855                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1856                         pri_rel(p->pri);
1857                         ast_mutex_unlock(&p->lock);
1858                 }
1859                 if (p->bearer || (p->sig == SIG_FXSKS)) {
1860                         if (p->bearer) {
1861                                 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);
1862                                 p->bearer->call = p->call;
1863                         } else
1864                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
1865                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1866                 }
1867                 p->digital = ast_test_flag(ast,AST_FLAG_DIGITAL);
1868                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1869                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1870                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : PRI_TRANS_CAP_SPEECH, 
1871                                         (p->digital ? -1 : 
1872                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1873                 dp_strip = 0;
1874                 pridialplan = p->pri->dialplan - 1;
1875                 if (pridialplan == -2) { /* compute dynamically */
1876                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1877                                 dp_strip = strlen(p->pri->internationalprefix);
1878                                 pridialplan = PRI_INTERNATIONAL_ISDN;
1879                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1880                                 dp_strip = strlen(p->pri->nationalprefix);
1881                                 pridialplan = PRI_NATIONAL_ISDN;
1882                         } else {
1883                                 pridialplan = PRI_LOCAL_ISDN;
1884                         }
1885                 }
1886                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  s ? 1 : 0);
1887
1888                 ldp_strip = 0;
1889                 prilocaldialplan = p->pri->localdialplan - 1;
1890                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
1891                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1892                                 ldp_strip = strlen(p->pri->internationalprefix);
1893                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
1894                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1895                                 ldp_strip = strlen(p->pri->nationalprefix);
1896                                 prilocaldialplan = PRI_NATIONAL_ISDN;
1897                         } else {
1898                                 prilocaldialplan = PRI_LOCAL_ISDN;
1899                         }
1900                 }
1901                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan, 
1902                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
1903                                                  PRES_NUMBER_NOT_AVAILABLE);
1904                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
1905                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1906                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
1907                                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
1908                         pri_rel(p->pri);
1909                         ast_mutex_unlock(&p->lock);
1910                         pri_sr_free(sr);
1911                         return -1;
1912                 }
1913                 pri_sr_free(sr);
1914                 ast_setstate(ast, AST_STATE_DIALING);
1915                 pri_rel(p->pri);
1916         }
1917 #endif          
1918         ast_mutex_unlock(&p->lock);
1919         return 0;
1920 }
1921
1922 static void destroy_zt_pvt(struct zt_pvt **pvt)
1923 {
1924         struct zt_pvt *p = *pvt;
1925         /* Remove channel from the list */
1926         if(p->prev)
1927                 p->prev->next = p->next;
1928         if(p->next)
1929                 p->next->prev = p->prev;
1930         ast_mutex_destroy(&p->lock);
1931         free(p);
1932         *pvt = NULL;
1933 }
1934
1935 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1936 {
1937         int owned = 0;
1938         int i = 0;
1939
1940         if (!now) {
1941                 if (cur->owner) {
1942                         owned = 1;
1943                 }
1944
1945                 for (i = 0; i < 3; i++) {
1946                         if (cur->subs[i].owner) {
1947                                 owned = 1;
1948                         }
1949                 }
1950                 if (!owned) {
1951                         if (prev) {
1952                                 prev->next = cur->next;
1953                                 if (prev->next)
1954                                         prev->next->prev = prev;
1955                                 else
1956                                         ifend = prev;
1957                         } else {
1958                                 iflist = cur->next;
1959                                 if (iflist)
1960                                         iflist->prev = NULL;
1961                                 else
1962                                         ifend = NULL;
1963                         }
1964                         if (cur->subs[SUB_REAL].zfd > -1) {
1965                                 zt_close(cur->subs[SUB_REAL].zfd);
1966                         }
1967                         destroy_zt_pvt(&cur);
1968                 }
1969         } else {
1970                 if (prev) {
1971                         prev->next = cur->next;
1972                         if (prev->next)
1973                                 prev->next->prev = prev;
1974                         else
1975                                 ifend = prev;
1976                 } else {
1977                         iflist = cur->next;
1978                         if (iflist)
1979                                 iflist->prev = NULL;
1980                         else
1981                                 ifend = NULL;
1982                 }
1983                 if (cur->subs[SUB_REAL].zfd > -1) {
1984                         zt_close(cur->subs[SUB_REAL].zfd);
1985                 }
1986                 destroy_zt_pvt(&cur);
1987         }
1988         return 0;
1989 }
1990
1991 #ifdef ZAPATA_PRI
1992 int pri_is_up(struct zt_pri *pri)
1993 {
1994         int x;
1995         for (x=0;x<NUM_DCHANS;x++) {
1996                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
1997                         return 1;
1998         }
1999         return 0;
2000 }
2001
2002 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2003 {
2004         bearer->owner = &inuse;
2005         bearer->realcall = crv;
2006         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2007         if (crv->subs[SUB_REAL].owner)
2008                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2009         crv->bearer = bearer;
2010         crv->call = bearer->call;
2011         crv->pri = pri;
2012         return 0;
2013 }
2014
2015 static char *pri_order(int level)
2016 {
2017         switch(level) {
2018         case 0:
2019                 return "Primary";
2020         case 1:
2021                 return "Secondary";
2022         case 2:
2023                 return "Tertiary";
2024         case 3:
2025                 return "Quaternary";
2026         default:
2027                 return "<Unknown>";
2028         }               
2029 }
2030
2031 int pri_find_dchan(struct zt_pri *pri)
2032 {
2033         int oldslot = -1;
2034         struct pri *old;
2035         int newslot = -1;
2036         int x;
2037         old = pri->pri;
2038         for(x=0;x<NUM_DCHANS;x++) {
2039                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2040                         newslot = x;
2041                 if (pri->dchans[x] == old) {
2042                         oldslot = x;
2043                 }
2044         }
2045         if (newslot < 0) {
2046                 newslot = 0;
2047                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
2048                         pri->dchannels[newslot]);
2049         }
2050         if (old && (oldslot != newslot))
2051                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2052                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2053         pri->pri = pri->dchans[newslot];
2054         return 0;
2055 }
2056 #endif
2057
2058 static int zt_hangup(struct ast_channel *ast)
2059 {
2060         int res;
2061         int index,x, law;
2062         /*static int restore_gains(struct zt_pvt *p);*/
2063         struct zt_pvt *p = ast->tech_pvt;
2064         struct zt_pvt *tmp = NULL;
2065         struct zt_pvt *prev = NULL;
2066         ZT_PARAMS par;
2067
2068         if (option_debug)
2069                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2070         if (!ast->tech_pvt) {
2071                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2072                 return 0;
2073         }
2074         
2075         ast_mutex_lock(&p->lock);
2076         
2077         index = zt_get_index(ast, p, 1);
2078
2079         if (p->sig == SIG_PRI) {
2080                 x = 1;
2081                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2082         }
2083
2084         x = 0;
2085         zt_confmute(p, 0);
2086         restore_gains(p);
2087         if (p->origcid_num) {
2088                 strncpy(p->cid_num, p->origcid_num, sizeof(p->cid_num) - 1);
2089                 free(p->origcid_num);
2090                 p->origcid_num = NULL;
2091         }       
2092         if (p->origcid_name) {
2093                 strncpy(p->cid_name, p->origcid_name, sizeof(p->cid_name) - 1);
2094                 free(p->origcid_name);
2095                 p->origcid_name = NULL;
2096         }       
2097         if (p->dsp)
2098                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2099         if (p->exten)
2100                 p->exten[0] = '\0';
2101
2102         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2103                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2104         p->ignoredtmf = 0;
2105         
2106         if (index > -1) {
2107                 /* Real channel, do some fixup */
2108                 p->subs[index].owner = NULL;
2109                 p->subs[index].needanswer = 0;
2110                 p->subs[index].needflash = 0;
2111                 p->subs[index].needringing = 0;
2112                 p->subs[index].needbusy = 0;
2113                 p->subs[index].needcongestion = 0;
2114                 p->subs[index].linear = 0;
2115                 p->subs[index].needcallerid = 0;
2116                 p->polarity = POLARITY_IDLE;
2117                 zt_setlinear(p->subs[index].zfd, 0);
2118                 if (index == SUB_REAL) {
2119                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2120                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2121                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2122                                         /* We had flipped over to answer a callwait and now it's gone */
2123                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2124                                         /* Move to the call-wait, but un-own us until they flip back. */
2125                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2126                                         unalloc_sub(p, SUB_CALLWAIT);
2127                                         p->owner = NULL;
2128                                 } else {
2129                                         /* The three way hung up, but we still have a call wait */
2130                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2131                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2132                                         unalloc_sub(p, SUB_THREEWAY);
2133                                         if (p->subs[SUB_REAL].inthreeway) {
2134                                                 /* This was part of a three way call.  Immediately make way for
2135                                                    another call */
2136                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2137                                                 p->owner = p->subs[SUB_REAL].owner;
2138                                         } else {
2139                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2140                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2141                                                 p->owner = NULL;
2142                                         }
2143                                         p->subs[SUB_REAL].inthreeway = 0;
2144                                 }
2145                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2146                                 /* Move to the call-wait and switch back to them. */
2147                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2148                                 unalloc_sub(p, SUB_CALLWAIT);
2149                                 p->owner = p->subs[SUB_REAL].owner;
2150                                 if (p->owner->_state != AST_STATE_UP)
2151                                         p->subs[SUB_REAL].needanswer = 1;
2152                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2153                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2154                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2155                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2156                                 unalloc_sub(p, SUB_THREEWAY);
2157                                 if (p->subs[SUB_REAL].inthreeway) {
2158                                         /* This was part of a three way call.  Immediately make way for
2159                                            another call */
2160                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2161                                         p->owner = p->subs[SUB_REAL].owner;
2162                                 } else {
2163                                         /* This call hasn't been completed yet...  Set owner to NULL */
2164                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2165                                         p->owner = NULL;
2166                                 }
2167                                 p->subs[SUB_REAL].inthreeway = 0;
2168                         }
2169                 } else if (index == SUB_CALLWAIT) {
2170                         /* Ditch the holding callwait call, and immediately make it availabe */
2171                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2172                                 /* This is actually part of a three way, placed on hold.  Place the third part
2173                                    on music on hold now */
2174                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2175                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2176                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2177                                 /* Make it the call wait now */
2178                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2179                                 unalloc_sub(p, SUB_THREEWAY);
2180                         } else
2181                                 unalloc_sub(p, SUB_CALLWAIT);
2182                 } else if (index == SUB_THREEWAY) {
2183                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2184                                 /* The other party of the three way call is currently in a call-wait state.
2185                                    Start music on hold for them, and take the main guy out of the third call */
2186                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2187                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2188                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2189                         }
2190                         p->subs[SUB_REAL].inthreeway = 0;
2191                         /* If this was part of a three way call index, let us make
2192                            another three way call */
2193                         unalloc_sub(p, SUB_THREEWAY);
2194                 } else {
2195                         /* This wasn't any sort of call, but how are we an index? */
2196                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2197                 }
2198         }
2199
2200
2201         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2202                 p->owner = NULL;
2203                 p->ringt = 0;
2204                 p->distinctivering = 0;
2205                 p->confirmanswer = 0;
2206                 p->cidrings = 1;
2207                 p->outgoing = 0;
2208                 p->digital = 0;
2209                 p->faxhandled = 0;
2210                 p->pulsedial = 0;
2211                 p->onhooktime = time(NULL);
2212 #ifdef ZAPATA_PRI
2213                 p->proceeding = 0;
2214                 p->setup_ack = 0;
2215 #endif          
2216                 if (p->dsp) {
2217                         ast_dsp_free(p->dsp);
2218                         p->dsp = NULL;
2219                 }
2220
2221                 law = ZT_LAW_DEFAULT;
2222                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2223                 if (res < 0) 
2224                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2225                 /* Perform low level hangup if no owner left */
2226 #ifdef ZAPATA_PRI
2227                 if (p->pri) {
2228                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2229                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2230                                 if (!pri_grab(p, p->pri)) {
2231                                         if (p->alreadyhungup) {
2232                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2233                                                 pri_hangup(p->pri->pri, p->call, -1);
2234                                                 p->call = NULL;
2235                                                 if (p->bearer) 
2236                                                         p->bearer->call = NULL;
2237                                         } else {
2238                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2239                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2240                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2241                                                 p->alreadyhungup = 1;
2242                                                 if (p->bearer)
2243                                                         p->bearer->alreadyhungup = 1;
2244                                                 if (cause) {
2245                                                         if (atoi(cause))
2246                                                                 icause = atoi(cause);
2247                                                 }
2248                                                 pri_hangup(p->pri->pri, p->call, icause);
2249                                         }
2250                                         if (res < 0) 
2251                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2252                                         pri_rel(p->pri);                        
2253                                 } else {
2254                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2255                                         res = -1;
2256                                 }
2257                         } else {
2258                                 if (p->bearer)
2259                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2260                                 p->call = NULL;
2261                                 res = 0;
2262                         }
2263                 }
2264 #endif
2265 #ifdef ZAPATA_R2
2266                 if (p->sig == SIG_R2) {
2267                         if (p->hasr2call) {
2268                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2269                                 p->hasr2call = 0;
2270                                 res = 0;
2271                         } else
2272                                 res = 0;
2273
2274                 }
2275 #endif
2276                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2277                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2278                 if (res < 0) {
2279                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2280                 }
2281                 switch(p->sig) {
2282                 case SIG_FXOGS:
2283                 case SIG_FXOLS:
2284                 case SIG_FXOKS:
2285                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2286                         if (!res) {
2287 #if 0
2288                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2289 #endif
2290                                 /* If they're off hook, try playing congestion */
2291                                 if ((par.rxisoffhook) && (!p->radio))
2292                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2293                                 else
2294                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2295                         }
2296                         break;
2297                 case SIG_FXSGS:
2298                 case SIG_FXSLS:
2299                 case SIG_FXSKS:
2300                         /* Make sure we're not made available for at least two seconds assuming
2301                            we were actually used for an inbound or outbound call. */
2302                         if (ast->_state != AST_STATE_RESERVED) {
2303                                 time(&p->guardtime);
2304                                 p->guardtime += 2;
2305                         }
2306                         break;
2307                 default:
2308                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2309                 }
2310                 if (p->cidspill)
2311                         free(p->cidspill);
2312                 if (p->sig)
2313                         zt_disable_ec(p);
2314                 x = 0;
2315                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2316                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2317                 p->didtdd = 0;
2318                 p->cidspill = NULL;
2319                 p->callwaitcas = 0;
2320                 p->callwaiting = p->permcallwaiting;
2321                 p->hidecallerid = p->permhidecallerid;
2322                 p->dialing = 0;
2323                 p->rdnis[0] = '\0';
2324                 update_conf(p);
2325                 reset_conf(p);
2326                 /* Restore data mode */
2327                 if (p->sig == SIG_PRI) {
2328                         x = 0;
2329                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2330                 }
2331 #ifdef ZAPATA_PRI
2332                 if (p->bearer) {
2333                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2334                         /* Free up the bearer channel as well, and
2335                            don't use its file descriptor anymore */
2336                         update_conf(p->bearer);
2337                         reset_conf(p->bearer);
2338                         p->bearer->owner = NULL;
2339                         p->bearer->realcall = NULL;
2340                         p->bearer = NULL;
2341                         p->subs[SUB_REAL].zfd = -1;
2342                         p->pri = NULL;
2343                 }
2344 #endif
2345                 restart_monitor();
2346         }
2347
2348
2349         p->callwaitingrepeat = 0;
2350         p->cidcwexpire = 0;
2351         ast->tech_pvt = NULL;
2352         ast_mutex_unlock(&p->lock);
2353         ast_mutex_lock(&usecnt_lock);
2354         usecnt--;
2355         if (usecnt < 0) 
2356                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2357         ast_mutex_unlock(&usecnt_lock);
2358         ast_update_use_count();
2359         if (option_verbose > 2) 
2360                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2361
2362         ast_mutex_lock(&iflock);
2363         tmp = iflist;
2364         prev = NULL;
2365         if (p->destroy) {
2366                 while (tmp) {
2367                         if (tmp == p) {
2368                                 destroy_channel(prev, tmp, 0);
2369                                 break;
2370                         } else {
2371                                 prev = tmp;
2372                                 tmp = tmp->next;
2373                         }
2374                 }
2375         }
2376         ast_mutex_unlock(&iflock);
2377         return 0;
2378 }
2379
2380 static int zt_answer(struct ast_channel *ast)
2381 {
2382         struct zt_pvt *p = ast->tech_pvt;
2383         int res=0;
2384         int index;
2385         int oldstate = ast->_state;
2386         ast_setstate(ast, AST_STATE_UP);
2387         ast_mutex_lock(&p->lock);
2388         index = zt_get_index(ast, p, 0);
2389         if (index < 0)
2390                 index = SUB_REAL;
2391         /* nothing to do if a radio channel */
2392         if (p->radio) {
2393                 ast_mutex_unlock(&p->lock);
2394                 return 0;
2395         }
2396         switch(p->sig) {
2397         case SIG_FXSLS:
2398         case SIG_FXSGS:
2399         case SIG_FXSKS:
2400                 p->ringt = 0;
2401                 /* Fall through */
2402         case SIG_EM:
2403         case SIG_EM_E1:
2404         case SIG_EMWINK:
2405         case SIG_FEATD:
2406         case SIG_FEATDMF:
2407         case SIG_E911:
2408         case SIG_FEATB:
2409         case SIG_SF:
2410         case SIG_SFWINK:
2411         case SIG_SF_FEATD:
2412         case SIG_SF_FEATDMF:
2413         case SIG_SF_FEATB:
2414         case SIG_FXOLS:
2415         case SIG_FXOGS:
2416         case SIG_FXOKS:
2417                 /* Pick up the line */
2418                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2419                 if(p->hanguponpolarityswitch) {
2420                         gettimeofday(&p->polaritydelaytv, NULL);
2421                 }
2422                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2423                 tone_zone_play_tone(p->subs[index].zfd, -1);
2424                 p->dialing = 0;
2425                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2426                         if (oldstate == AST_STATE_RINGING) {
2427                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2428                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2429                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2430                                 p->owner = p->subs[SUB_REAL].owner;
2431                         }
2432                 }
2433                 if (p->sig & __ZT_SIG_FXS) {
2434                         zt_enable_ec(p);
2435                         zt_train_ec(p);
2436                 }
2437                 break;
2438 #ifdef ZAPATA_PRI
2439         case SIG_PRI:
2440                 /* Send a pri acknowledge */
2441                 if (!pri_grab(p, p->pri)) {
2442                         p->proceeding = 2;
2443                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2444                         pri_rel(p->pri);
2445                 } else {
2446                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2447                         res= -1;
2448                 }
2449                 break;
2450 #endif
2451 #ifdef ZAPATA_R2
2452         case SIG_R2:
2453                 res = mfcr2_AnswerCall(p->r2, NULL);
2454                 if (res)
2455                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2456                 break;
2457 #endif                  
2458         case 0:
2459                 ast_mutex_unlock(&p->lock);
2460                 return 0;
2461         default:
2462                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2463                 res = -1;
2464         }
2465         ast_mutex_unlock(&p->lock);
2466         return res;
2467 }
2468
2469 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2470 {
2471 char    *cp;
2472 int     x;
2473
2474         struct zt_pvt *p = chan->tech_pvt;
2475
2476         
2477         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2478                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2479            {
2480                 errno = ENOSYS;
2481                 return -1;
2482            }
2483         cp = (char *)data;
2484         if ((!cp) || (datalen < 1))
2485            {
2486                 errno = EINVAL;
2487                 return -1;
2488            }
2489         switch(option) {
2490             case AST_OPTION_TONE_VERIFY:
2491                 if (!p->dsp)
2492                         break;
2493                 switch(*cp) {
2494                     case 1:
2495                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2496                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2497                         break;
2498                     case 2:
2499                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2500                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2501                         break;
2502                     default:
2503                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2504                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2505                         break;
2506                 }
2507                 break;
2508             case AST_OPTION_TDD:  /* turn on or off TDD */
2509                 if (!*cp) { /* turn it off */
2510                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2511                         if (p->tdd) tdd_free(p->tdd);
2512                         p->tdd = 0;
2513                         p->mate = 0;
2514                         break;
2515                 }
2516                 if (*cp == 2)
2517                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2518                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2519                 p->mate = 0;
2520                 zt_disable_ec(p);
2521                 /* otherwise, turn it on */
2522                 if (!p->didtdd) { /* if havent done it yet */
2523                         unsigned char mybuf[41000],*buf;
2524                         int size,res,fd,len;
2525                         int index;
2526                         struct pollfd fds[1];
2527                         buf = mybuf;
2528                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2529                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2530                         len = 40000;
2531                         index = zt_get_index(chan, p, 0);
2532                         if (index < 0) {
2533                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2534                                 return -1;
2535                         }
2536                         fd = p->subs[index].zfd;
2537                         while(len) {
2538                                 if (ast_check_hangup(chan)) return -1;
2539                                 size = len;
2540                                 if (size > READ_SIZE)
2541                                         size = READ_SIZE;
2542                                 fds[0].fd = fd;
2543                                 fds[0].events = POLLPRI | POLLOUT;
2544                                 res = poll(fds, 1, -1);
2545                                 if (!res) {
2546                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2547                                         continue;
2548                                 }
2549                                   /* if got exception */
2550                                 if (fds[0].revents & POLLPRI) return -1;
2551                                 if (!(fds[0].revents & POLLOUT)) {
2552                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2553                                         continue;
2554                                 }
2555                                 res = write(fd, buf, size);
2556                                 if (res != size) {
2557                                         if (res == -1) return -1;
2558                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2559                                         break;
2560                                 }
2561                                 len -= size;
2562                                 buf += size;
2563                         }
2564                         p->didtdd = 1; /* set to have done it now */            
2565                 }
2566                 if (*cp == 2) { /* Mate mode */
2567                         if (p->tdd) tdd_free(p->tdd);
2568                         p->tdd = 0;
2569                         p->mate = 1;
2570                         break;
2571                         }               
2572                 if (!p->tdd) { /* if we dont have one yet */
2573                         p->tdd = tdd_new(); /* allocate one */
2574                 }               
2575                 break;
2576             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2577                 if (!*cp)
2578                 {               
2579                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2580                         x = 0;
2581                 }
2582                 else
2583                 {               
2584                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2585                         x = 1;
2586                 }
2587                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2588                 break;
2589             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2590                 if (!*cp)
2591                 {               
2592                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2593                         x = 0;
2594                         zt_disable_ec(p);
2595                 }
2596                 else
2597                 {               
2598                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2599                         x = 1;
2600                 }
2601                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2602                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2603                 break;
2604         }
2605         errno = 0;
2606         return 0;
2607 }
2608
2609 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2610 {
2611         /* Unlink a specific slave or all slaves/masters from a given master */
2612         int x;
2613         int hasslaves;
2614         if (!master)
2615                 return;
2616         if (needlock) {
2617                 ast_mutex_lock(&master->lock);
2618                 if (slave) {
2619                         while(ast_mutex_trylock(&slave->lock)) {
2620                                 ast_mutex_unlock(&master->lock);
2621                                 usleep(1);
2622                                 ast_mutex_lock(&master->lock);
2623                         }
2624                 }
2625         }
2626         hasslaves = 0;
2627         for (x=0;x<MAX_SLAVES;x++) {
2628                 if (master->slaves[x]) {
2629                         if (!slave || (master->slaves[x] == slave)) {
2630                                 /* Take slave out of the conference */
2631                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2632                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2633                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2634                                 master->slaves[x]->master = NULL;
2635                                 master->slaves[x] = NULL;
2636                         } else
2637                                 hasslaves = 1;
2638                 }
2639                 if (!hasslaves)
2640                         master->inconference = 0;
2641         }
2642         if (!slave) {
2643                 if (master->master) {
2644                         /* Take master out of the conference */
2645                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2646                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2647                         hasslaves = 0;
2648                         for (x=0;x<MAX_SLAVES;x++) {
2649                                 if (master->master->slaves[x] == master)
2650                                         master->master->slaves[x] = NULL;
2651                                 else if (master->master->slaves[x])
2652                                         hasslaves = 1;
2653                         }
2654                         if (!hasslaves)
2655                                 master->master->inconference = 0;
2656                 }
2657                 master->master = NULL;
2658         }
2659         update_conf(master);
2660         if (needlock) {
2661                 if (slave)
2662                         ast_mutex_unlock(&slave->lock);
2663                 ast_mutex_unlock(&master->lock);
2664         }
2665 }
2666
2667 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2668         int x;
2669         if (!slave || !master) {
2670                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2671                 return;
2672         }
2673         for (x=0;x<MAX_SLAVES;x++) {
2674                 if (!master->slaves[x]) {
2675                         master->slaves[x] = slave;
2676                         break;
2677                 }
2678         }
2679         if (x >= MAX_SLAVES) {
2680                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2681                 master->slaves[MAX_SLAVES - 1] = slave;
2682         }
2683         if (slave->master) 
2684                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2685         slave->master = master;
2686         
2687         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2688 }
2689
2690 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2691 {
2692         struct ast_channel *who = NULL, *cs[3];
2693         struct zt_pvt *p0, *p1, *op0, *op1;
2694         struct zt_pvt *master=NULL, *slave=NULL;
2695         struct ast_frame *f;
2696         int to;
2697         int inconf = 0;
2698         int nothingok = 0;
2699         int ofd1, ofd2;
2700         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2701         int os1 = -1, os2 = -1;
2702         struct ast_channel *oc1, *oc2;
2703 #ifdef PRI_2BCT
2704         int triedtopribridge = 0;
2705         q931_call *q931c0 = NULL, *q931c1 = NULL;
2706 #endif
2707
2708
2709         /* if need DTMF, cant native bridge */
2710         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2711                 return -2;
2712                 
2713                 
2714         ast_mutex_lock(&c0->lock);
2715         ast_mutex_lock(&c1->lock);
2716
2717         p0 = c0->tech_pvt;
2718         p1 = c1->tech_pvt;
2719         /* cant do pseudo-channels here */
2720         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2721                 ast_mutex_unlock(&c0->lock);
2722                 ast_mutex_unlock(&c1->lock);
2723                 return -2;
2724         }
2725
2726         op0 = p0 = c0->tech_pvt;
2727         op1 = p1 = c1->tech_pvt;
2728         ofd1 = c0->fds[0];
2729         ofd2 = c1->fds[0];
2730         oi1 = zt_get_index(c0, p0, 0);
2731         oi2 = zt_get_index(c1, p1, 0);
2732         oc1 = p0->owner;
2733         oc2 = p1->owner;
2734         if ((oi1 < 0) || (oi2 < 0)) {
2735                 ast_mutex_unlock(&c0->lock);
2736                 ast_mutex_unlock(&c1->lock);
2737                 return -1;
2738         }
2739
2740
2741
2742         ast_mutex_lock(&p0->lock);
2743         if (ast_mutex_trylock(&p1->lock)) {
2744                 /* Don't block, due to potential for deadlock */
2745                 ast_mutex_unlock(&p0->lock);
2746                 ast_mutex_unlock(&c0->lock);
2747                 ast_mutex_unlock(&c1->lock);
2748                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2749                 return -3;
2750         }
2751         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2752                 if (!p0->owner || !p1->owner) {
2753                         /* Currently unowned -- Do nothing.  */
2754                         nothingok = 1;
2755                 } else {
2756                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2757                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2758                                 master = p0;
2759                                 slave = p1;
2760                                 inconf = 1;
2761                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2762                                 master = p1;
2763                                 slave = p0;
2764                                 inconf = 1;
2765                         } else {
2766                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2767                                 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,
2768                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2769                         }
2770                 }
2771         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2772                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2773                         master = p1;
2774                         slave = p0;
2775                 } else {
2776                         nothingok = 1;
2777                 }
2778         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2779                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2780                         master = p0;
2781                         slave = p1;
2782                 } else {
2783                         nothingok  = 1;
2784                 }
2785         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2786                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2787                    don't put us in anything */
2788                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2789                         master = p1;
2790                         slave = p0;
2791                 } else {
2792                         nothingok = 1;
2793                 }
2794         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2795                 /* Same as previous */
2796                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2797                         master = p0;
2798                         slave = p1;
2799                 } else {
2800                         nothingok = 1;
2801                 }
2802         }
2803         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2804                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2805         if (master && slave) {
2806                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2807                    in an active threeway call with a channel that is ringing, we should
2808                    indicate ringing. */
2809                 if ((oi2 == SUB_THREEWAY) && 
2810                         p1->subs[SUB_THREEWAY].inthreeway && 
2811                         p1->subs[SUB_REAL].owner && 
2812                         p1->subs[SUB_REAL].inthreeway && 
2813                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2814                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2815                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2816                                 os2 = p1->subs[SUB_REAL].owner->_state;
2817                 } else {
2818                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2819                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2820                 }
2821                 if ((oi1 == SUB_THREEWAY) && 
2822                         p0->subs[SUB_THREEWAY].inthreeway && 
2823                         p0->subs[SUB_REAL].owner && 
2824                         p0->subs[SUB_REAL].inthreeway && 
2825                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2826                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2827                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2828                                 os1 = p0->subs[SUB_REAL].owner->_state;
2829                 } else {
2830                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2831                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2832                 }
2833                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2834                         if (!p0->echocanbridged || !p1->echocanbridged) {
2835                                 /* Disable echo cancellation if appropriate */
2836                                 zt_disable_ec(p0);
2837                                 zt_disable_ec(p1);
2838                         }
2839                 }
2840                 zt_link(slave, master);
2841                 master->inconference = inconf;
2842         } else if (!nothingok)
2843                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2844
2845         update_conf(p0);
2846         update_conf(p1);
2847         t1 = p0->subs[SUB_REAL].inthreeway;
2848         t2 = p1->subs[SUB_REAL].inthreeway;
2849
2850         ast_mutex_unlock(&p0->lock);
2851         ast_mutex_unlock(&p1->lock);
2852
2853         ast_mutex_unlock(&c0->lock);
2854         ast_mutex_unlock(&c1->lock);
2855
2856         /* Native bridge failed */
2857         if ((!master || !slave) && !nothingok) {
2858                 if (op0 == p0)
2859                         zt_enable_ec(p0);
2860                 if (op1 == p1)
2861                         zt_enable_ec(p1);
2862                 return -1;
2863         }
2864         
2865         cs[0] = c0;
2866         cs[1] = c1;
2867         cs[2] = NULL;
2868         for (;;) {
2869                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2870                    and then balking if anything is wrong */
2871                 ast_mutex_lock(&c0->lock);
2872                 ast_mutex_lock(&c1->lock);
2873                 p0 = c0->tech_pvt;
2874                 p1 = c1->tech_pvt;
2875
2876 #ifdef PRI_2BCT
2877                 q931c0 = p0->call;
2878                 q931c1 = p1->call;
2879                 if (p0->transfer && p1->transfer 
2880                                 && q931c0 && q931c1 
2881                                 && !triedtopribridge) {
2882
2883                         pri_channel_bridge(q931c0, q931c1);
2884                         triedtopribridge = 1;
2885                 }
2886 #endif
2887                 if (op0 == p0)
2888                         i1 = zt_get_index(c0, p0, 1);
2889                 if (op1 == p1)
2890                         i2 = zt_get_index(c1, p1, 1);
2891                 ast_mutex_unlock(&c0->lock);
2892                 ast_mutex_unlock(&c1->lock);
2893                 if ((op0 != p0) || (op1 != p1) || 
2894                     (ofd1 != c0->fds[0]) || 
2895                         (ofd2 != c1->fds[0]) ||
2896                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2897                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2898                     (oc1 != p0->owner) || 
2899                         (oc2 != p1->owner) ||
2900                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2901                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2902                         (oi1 != i1) ||
2903                         (oi2 != i2)) {
2904                         if (slave && master)
2905                                 zt_unlink(slave, master, 1);
2906                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2907                                                                         op0->channel, oi1, op1->channel, oi2);
2908                         if (op0 == p0)
2909                                 zt_enable_ec(p0);
2910                         if (op1 == p1)
2911                                 zt_enable_ec(p1);
2912                         return -3;
2913                 }
2914                 to = -1;
2915                 who = ast_waitfor_n(cs, 2, &to);
2916                 if (!who) {
2917                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2918                         continue;
2919                 }
2920                 if (who->tech_pvt == op0) 
2921                         op0->ignoredtmf = 1;
2922                 else if (who->tech_pvt == op1)
2923                         op1->ignoredtmf = 1;
2924                 f = ast_read(who);
2925                 if (who->tech_pvt == op0) 
2926                         op0->ignoredtmf = 0;
2927                 else if (who->tech_pvt == op1)
2928                         op1->ignoredtmf = 0;
2929                 if (!f) {
2930                         *fo = NULL;
2931                         *rc = who;
2932                         if (slave && master)
2933                                 zt_unlink(slave, master, 1);
2934                         if (op0 == p0)
2935                                 zt_enable_ec(p0);
2936                         if (op1 == p1)
2937                                 zt_enable_ec(p1);
2938                         return 0;
2939                 }
2940                 if (f->frametype == AST_FRAME_CONTROL) {
2941                         *fo = f;
2942                         *rc = who;
2943                         if (slave && master)
2944                                 zt_unlink(slave, master, 1);
2945                         return 0;
2946                 }
2947                 if (f->frametype == AST_FRAME_DTMF) {
2948                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2949                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2950                                 *fo = f;
2951                                 *rc = who;
2952                                 if (slave && master)
2953                                         zt_unlink(slave, master, 1);
2954                                 return 0;
2955                         } else if ((who == c0) && p0->pulsedial) {
2956                                 ast_write(c1, f);
2957                         } else if ((who == c1) && p1->pulsedial) {
2958                                 ast_write(c0, f);
2959                         }
2960                 }
2961                 ast_frfree(f);
2962
2963                 /* Swap who gets priority */
2964                 cs[2] = cs[0];
2965                 cs[0] = cs[1];
2966                 cs[1] = cs[2];
2967         }
2968 }
2969
2970 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2971 {
2972         struct zt_pvt *p = newchan->tech_pvt;
2973         int x;
2974         ast_mutex_lock(&p->lock);
2975         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2976         if (p->owner == oldchan) {
2977                 p->owner = newchan;
2978         }
2979         for (x=0;x<3;x++)
2980                 if (p->subs[x].owner == oldchan) {
2981                         if (!x)
2982                                 zt_unlink(NULL, p, 0);
2983                         p->subs[x].owner = newchan;
2984                 }
2985         if (newchan->_state == AST_STATE_RINGING) 
2986                 zt_indicate(newchan, AST_CONTROL_RINGING);
2987         update_conf(p);