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