2926fc3421e391f50c5f52083df5d56f9ae0323d
[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_REDIRECTING_REASON
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))
1839                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1840                                 else
1841                                         p->dop.dialstr[0] = '\0';
1842                                 *s = '\0';
1843                         } else {
1844                                 p->dop.dialstr[0] = '\0';
1845                         }
1846                 }
1847                 if (pri_grab(p, p->pri)) {
1848                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1849                         ast_mutex_unlock(&p->lock);
1850                         return -1;
1851                 }
1852                 if (!(p->call = pri_new_call(p->pri->pri))) {
1853                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1854                         pri_rel(p->pri);
1855                         ast_mutex_unlock(&p->lock);
1856                         return -1;
1857                 }
1858                 if (!(sr = pri_sr_new())) {
1859                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1860                         pri_rel(p->pri);
1861                         ast_mutex_unlock(&p->lock);
1862                 }
1863                 if (p->bearer || (p->sig == SIG_FXSKS)) {
1864                         if (p->bearer) {
1865                                 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);
1866                                 p->bearer->call = p->call;
1867                         } else
1868                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
1869                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1870                 }
1871                 p->digital = IS_DIGITAL(ast->transfercapability);
1872                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1873                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1874                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
1875                                         (p->digital ? -1 : 
1876                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1877                 if (option_verbose > 2)
1878                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
1879                 dp_strip = 0;
1880                 pridialplan = p->pri->dialplan - 1;
1881                 if (pridialplan == -2) { /* compute dynamically */
1882                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1883                                 dp_strip = strlen(p->pri->internationalprefix);
1884                                 pridialplan = PRI_INTERNATIONAL_ISDN;
1885                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1886                                 dp_strip = strlen(p->pri->nationalprefix);
1887                                 pridialplan = PRI_NATIONAL_ISDN;
1888                         } else {
1889                                 pridialplan = PRI_LOCAL_ISDN;
1890                         }
1891                 }
1892                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  s ? 1 : 0);
1893
1894                 ldp_strip = 0;
1895                 prilocaldialplan = p->pri->localdialplan - 1;
1896                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
1897                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1898                                 ldp_strip = strlen(p->pri->internationalprefix);
1899                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
1900                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1901                                 ldp_strip = strlen(p->pri->nationalprefix);
1902                                 prilocaldialplan = PRI_NATIONAL_ISDN;
1903                         } else {
1904                                 prilocaldialplan = PRI_LOCAL_ISDN;
1905                         }
1906                 }
1907                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan, 
1908                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
1909                                                  PRES_NUMBER_NOT_AVAILABLE);
1910                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
1911                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1912                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
1913                                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
1914                         pri_rel(p->pri);
1915                         ast_mutex_unlock(&p->lock);
1916                         pri_sr_free(sr);
1917                         return -1;
1918                 }
1919                 pri_sr_free(sr);
1920                 ast_setstate(ast, AST_STATE_DIALING);
1921                 pri_rel(p->pri);
1922         }
1923 #endif          
1924         ast_mutex_unlock(&p->lock);
1925         return 0;
1926 }
1927
1928 static void destroy_zt_pvt(struct zt_pvt **pvt)
1929 {
1930         struct zt_pvt *p = *pvt;
1931         /* Remove channel from the list */
1932         if(p->prev)
1933                 p->prev->next = p->next;
1934         if(p->next)
1935                 p->next->prev = p->prev;
1936         ast_mutex_destroy(&p->lock);
1937         free(p);
1938         *pvt = NULL;
1939 }
1940
1941 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1942 {
1943         int owned = 0;
1944         int i = 0;
1945
1946         if (!now) {
1947                 if (cur->owner) {
1948                         owned = 1;
1949                 }
1950
1951                 for (i = 0; i < 3; i++) {
1952                         if (cur->subs[i].owner) {
1953                                 owned = 1;
1954                         }
1955                 }
1956                 if (!owned) {
1957                         if (prev) {
1958                                 prev->next = cur->next;
1959                                 if (prev->next)
1960                                         prev->next->prev = prev;
1961                                 else
1962                                         ifend = prev;
1963                         } else {
1964                                 iflist = cur->next;
1965                                 if (iflist)
1966                                         iflist->prev = NULL;
1967                                 else
1968                                         ifend = NULL;
1969                         }
1970                         if (cur->subs[SUB_REAL].zfd > -1) {
1971                                 zt_close(cur->subs[SUB_REAL].zfd);
1972                         }
1973                         destroy_zt_pvt(&cur);
1974                 }
1975         } else {
1976                 if (prev) {
1977                         prev->next = cur->next;
1978                         if (prev->next)
1979                                 prev->next->prev = prev;
1980                         else
1981                                 ifend = prev;
1982                 } else {
1983                         iflist = cur->next;
1984                         if (iflist)
1985                                 iflist->prev = NULL;
1986                         else
1987                                 ifend = NULL;
1988                 }
1989                 if (cur->subs[SUB_REAL].zfd > -1) {
1990                         zt_close(cur->subs[SUB_REAL].zfd);
1991                 }
1992                 destroy_zt_pvt(&cur);
1993         }
1994         return 0;
1995 }
1996
1997 #ifdef ZAPATA_PRI
1998 int pri_is_up(struct zt_pri *pri)
1999 {
2000         int x;
2001         for (x=0;x<NUM_DCHANS;x++) {
2002                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2003                         return 1;
2004         }
2005         return 0;
2006 }
2007
2008 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2009 {
2010         bearer->owner = &inuse;
2011         bearer->realcall = crv;
2012         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2013         if (crv->subs[SUB_REAL].owner)
2014                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2015         crv->bearer = bearer;
2016         crv->call = bearer->call;
2017         crv->pri = pri;
2018         return 0;
2019 }
2020
2021 static char *pri_order(int level)
2022 {
2023         switch(level) {
2024         case 0:
2025                 return "Primary";
2026         case 1:
2027                 return "Secondary";
2028         case 2:
2029                 return "Tertiary";
2030         case 3:
2031                 return "Quaternary";
2032         default:
2033                 return "<Unknown>";
2034         }               
2035 }
2036
2037 int pri_find_dchan(struct zt_pri *pri)
2038 {
2039         int oldslot = -1;
2040         struct pri *old;
2041         int newslot = -1;
2042         int x;
2043         old = pri->pri;
2044         for(x=0;x<NUM_DCHANS;x++) {
2045                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2046                         newslot = x;
2047                 if (pri->dchans[x] == old) {
2048                         oldslot = x;
2049                 }
2050         }
2051         if (newslot < 0) {
2052                 newslot = 0;
2053                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
2054                         pri->dchannels[newslot]);
2055         }
2056         if (old && (oldslot != newslot))
2057                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2058                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2059         pri->pri = pri->dchans[newslot];
2060         return 0;
2061 }
2062 #endif
2063
2064 static int zt_hangup(struct ast_channel *ast)
2065 {
2066         int res;
2067         int index,x, law;
2068         /*static int restore_gains(struct zt_pvt *p);*/
2069         struct zt_pvt *p = ast->tech_pvt;
2070         struct zt_pvt *tmp = NULL;
2071         struct zt_pvt *prev = NULL;
2072         ZT_PARAMS par;
2073
2074         if (option_debug)
2075                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2076         if (!ast->tech_pvt) {
2077                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2078                 return 0;
2079         }
2080         
2081         ast_mutex_lock(&p->lock);
2082         
2083         index = zt_get_index(ast, p, 1);
2084
2085         if (p->sig == SIG_PRI) {
2086                 x = 1;
2087                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2088         }
2089
2090         x = 0;
2091         zt_confmute(p, 0);
2092         restore_gains(p);
2093         if (p->origcid_num) {
2094                 strncpy(p->cid_num, p->origcid_num, sizeof(p->cid_num) - 1);
2095                 free(p->origcid_num);
2096                 p->origcid_num = NULL;
2097         }       
2098         if (p->origcid_name) {
2099                 strncpy(p->cid_name, p->origcid_name, sizeof(p->cid_name) - 1);
2100                 free(p->origcid_name);
2101                 p->origcid_name = NULL;
2102         }       
2103         if (p->dsp)
2104                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2105         if (p->exten)
2106                 p->exten[0] = '\0';
2107
2108         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2109                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2110         p->ignoredtmf = 0;
2111         
2112         if (index > -1) {
2113                 /* Real channel, do some fixup */
2114                 p->subs[index].owner = NULL;
2115                 p->subs[index].needanswer = 0;
2116                 p->subs[index].needflash = 0;
2117                 p->subs[index].needringing = 0;
2118                 p->subs[index].needbusy = 0;
2119                 p->subs[index].needcongestion = 0;
2120                 p->subs[index].linear = 0;
2121                 p->subs[index].needcallerid = 0;
2122                 p->polarity = POLARITY_IDLE;
2123                 zt_setlinear(p->subs[index].zfd, 0);
2124                 if (index == SUB_REAL) {
2125                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2126                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2127                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2128                                         /* We had flipped over to answer a callwait and now it's gone */
2129                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2130                                         /* Move to the call-wait, but un-own us until they flip back. */
2131                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2132                                         unalloc_sub(p, SUB_CALLWAIT);
2133                                         p->owner = NULL;
2134                                 } else {
2135                                         /* The three way hung up, but we still have a call wait */
2136                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2137                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2138                                         unalloc_sub(p, SUB_THREEWAY);
2139                                         if (p->subs[SUB_REAL].inthreeway) {
2140                                                 /* This was part of a three way call.  Immediately make way for
2141                                                    another call */
2142                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2143                                                 p->owner = p->subs[SUB_REAL].owner;
2144                                         } else {
2145                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2146                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2147                                                 p->owner = NULL;
2148                                         }
2149                                         p->subs[SUB_REAL].inthreeway = 0;
2150                                 }
2151                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2152                                 /* Move to the call-wait and switch back to them. */
2153                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2154                                 unalloc_sub(p, SUB_CALLWAIT);
2155                                 p->owner = p->subs[SUB_REAL].owner;
2156                                 if (p->owner->_state != AST_STATE_UP)
2157                                         p->subs[SUB_REAL].needanswer = 1;
2158                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2159                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2160                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2161                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2162                                 unalloc_sub(p, SUB_THREEWAY);
2163                                 if (p->subs[SUB_REAL].inthreeway) {
2164                                         /* This was part of a three way call.  Immediately make way for
2165                                            another call */
2166                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2167                                         p->owner = p->subs[SUB_REAL].owner;
2168                                 } else {
2169                                         /* This call hasn't been completed yet...  Set owner to NULL */
2170                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2171                                         p->owner = NULL;
2172                                 }
2173                                 p->subs[SUB_REAL].inthreeway = 0;
2174                         }
2175                 } else if (index == SUB_CALLWAIT) {
2176                         /* Ditch the holding callwait call, and immediately make it availabe */
2177                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2178                                 /* This is actually part of a three way, placed on hold.  Place the third part
2179                                    on music on hold now */
2180                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2181                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2182                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2183                                 /* Make it the call wait now */
2184                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2185                                 unalloc_sub(p, SUB_THREEWAY);
2186                         } else
2187                                 unalloc_sub(p, SUB_CALLWAIT);
2188                 } else if (index == SUB_THREEWAY) {
2189                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2190                                 /* The other party of the three way call is currently in a call-wait state.
2191                                    Start music on hold for them, and take the main guy out of the third call */
2192                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2193                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2194                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2195                         }
2196                         p->subs[SUB_REAL].inthreeway = 0;
2197                         /* If this was part of a three way call index, let us make
2198                            another three way call */
2199                         unalloc_sub(p, SUB_THREEWAY);
2200                 } else {
2201                         /* This wasn't any sort of call, but how are we an index? */
2202                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2203                 }
2204         }
2205
2206
2207         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2208                 p->owner = NULL;
2209                 p->ringt = 0;
2210                 p->distinctivering = 0;
2211                 p->confirmanswer = 0;
2212                 p->cidrings = 1;
2213                 p->outgoing = 0;
2214                 p->digital = 0;
2215                 p->faxhandled = 0;
2216                 p->pulsedial = 0;
2217                 p->onhooktime = time(NULL);
2218 #ifdef ZAPATA_PRI
2219                 p->proceeding = 0;
2220                 p->alerting = 0;
2221                 p->setup_ack = 0;
2222 #endif          
2223                 if (p->dsp) {
2224                         ast_dsp_free(p->dsp);
2225                         p->dsp = NULL;
2226                 }
2227
2228                 law = ZT_LAW_DEFAULT;
2229                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2230                 if (res < 0) 
2231                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2232                 /* Perform low level hangup if no owner left */
2233 #ifdef ZAPATA_PRI
2234                 if (p->pri) {
2235                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2236                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2237                                 if (!pri_grab(p, p->pri)) {
2238                                         if (p->alreadyhungup) {
2239                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2240                                                 pri_hangup(p->pri->pri, p->call, -1);
2241                                                 p->call = NULL;
2242                                                 if (p->bearer) 
2243                                                         p->bearer->call = NULL;
2244                                         } else {
2245                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2246                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2247                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2248                                                 p->alreadyhungup = 1;
2249                                                 if (p->bearer)
2250                                                         p->bearer->alreadyhungup = 1;
2251                                                 if (cause) {
2252                                                         if (atoi(cause))
2253                                                                 icause = atoi(cause);
2254                                                 }
2255                                                 pri_hangup(p->pri->pri, p->call, icause);
2256                                         }
2257                                         if (res < 0) 
2258                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2259                                         pri_rel(p->pri);                        
2260                                 } else {
2261                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2262                                         res = -1;
2263                                 }
2264                         } else {
2265                                 if (p->bearer)
2266                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2267                                 p->call = NULL;
2268                                 res = 0;
2269                         }
2270                 }
2271 #endif
2272 #ifdef ZAPATA_R2
2273                 if (p->sig == SIG_R2) {
2274                         if (p->hasr2call) {
2275                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2276                                 p->hasr2call = 0;
2277                                 res = 0;
2278                         } else
2279                                 res = 0;
2280
2281                 }
2282 #endif
2283                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2284                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2285                 if (res < 0) {
2286                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2287                 }
2288                 switch(p->sig) {
2289                 case SIG_FXOGS:
2290                 case SIG_FXOLS:
2291                 case SIG_FXOKS:
2292                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2293                         if (!res) {
2294 #if 0
2295                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2296 #endif
2297                                 /* If they're off hook, try playing congestion */
2298                                 if ((par.rxisoffhook) && (!p->radio))
2299                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2300                                 else
2301                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2302                         }
2303                         break;
2304                 case SIG_FXSGS:
2305                 case SIG_FXSLS:
2306                 case SIG_FXSKS:
2307                         /* Make sure we're not made available for at least two seconds assuming
2308                            we were actually used for an inbound or outbound call. */
2309                         if (ast->_state != AST_STATE_RESERVED) {
2310                                 time(&p->guardtime);
2311                                 p->guardtime += 2;
2312                         }
2313                         break;
2314                 default:
2315                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2316                 }
2317                 if (p->cidspill)
2318                         free(p->cidspill);
2319                 if (p->sig)
2320                         zt_disable_ec(p);
2321                 x = 0;
2322                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2323                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2324                 p->didtdd = 0;
2325                 p->cidspill = NULL;
2326                 p->callwaitcas = 0;
2327                 p->callwaiting = p->permcallwaiting;
2328                 p->hidecallerid = p->permhidecallerid;
2329                 p->dialing = 0;
2330                 p->rdnis[0] = '\0';
2331                 update_conf(p);
2332                 reset_conf(p);
2333                 /* Restore data mode */
2334                 if (p->sig == SIG_PRI) {
2335                         x = 0;
2336                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2337                 }
2338 #ifdef ZAPATA_PRI
2339                 if (p->bearer) {
2340                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2341                         /* Free up the bearer channel as well, and
2342                            don't use its file descriptor anymore */
2343                         update_conf(p->bearer);
2344                         reset_conf(p->bearer);
2345                         p->bearer->owner = NULL;
2346                         p->bearer->realcall = NULL;
2347                         p->bearer = NULL;
2348                         p->subs[SUB_REAL].zfd = -1;
2349                         p->pri = NULL;
2350                 }
2351 #endif
2352                 restart_monitor();
2353         }
2354
2355
2356         p->callwaitingrepeat = 0;
2357         p->cidcwexpire = 0;
2358         ast->tech_pvt = NULL;
2359         ast_mutex_unlock(&p->lock);
2360         ast_mutex_lock(&usecnt_lock);
2361         usecnt--;
2362         if (usecnt < 0) 
2363                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2364         ast_mutex_unlock(&usecnt_lock);
2365         ast_update_use_count();
2366         if (option_verbose > 2) 
2367                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2368
2369         ast_mutex_lock(&iflock);
2370         tmp = iflist;
2371         prev = NULL;
2372         if (p->destroy) {
2373                 while (tmp) {
2374                         if (tmp == p) {
2375                                 destroy_channel(prev, tmp, 0);
2376                                 break;
2377                         } else {
2378                                 prev = tmp;
2379                                 tmp = tmp->next;
2380                         }
2381                 }
2382         }
2383         ast_mutex_unlock(&iflock);
2384         return 0;
2385 }
2386
2387 static int zt_answer(struct ast_channel *ast)
2388 {
2389         struct zt_pvt *p = ast->tech_pvt;
2390         int res=0;
2391         int index;
2392         int oldstate = ast->_state;
2393         ast_setstate(ast, AST_STATE_UP);
2394         ast_mutex_lock(&p->lock);
2395         index = zt_get_index(ast, p, 0);
2396         if (index < 0)
2397                 index = SUB_REAL;
2398         /* nothing to do if a radio channel */
2399         if (p->radio) {
2400                 ast_mutex_unlock(&p->lock);
2401                 return 0;
2402         }
2403         switch(p->sig) {
2404         case SIG_FXSLS:
2405         case SIG_FXSGS:
2406         case SIG_FXSKS:
2407                 p->ringt = 0;
2408                 /* Fall through */
2409         case SIG_EM:
2410         case SIG_EM_E1:
2411         case SIG_EMWINK:
2412         case SIG_FEATD:
2413         case SIG_FEATDMF:
2414         case SIG_E911:
2415         case SIG_FEATB:
2416         case SIG_SF:
2417         case SIG_SFWINK:
2418         case SIG_SF_FEATD:
2419         case SIG_SF_FEATDMF:
2420         case SIG_SF_FEATB:
2421         case SIG_FXOLS:
2422         case SIG_FXOGS:
2423         case SIG_FXOKS:
2424                 /* Pick up the line */
2425                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2426                 if(p->hanguponpolarityswitch) {
2427                         gettimeofday(&p->polaritydelaytv, NULL);
2428                 }
2429                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2430                 tone_zone_play_tone(p->subs[index].zfd, -1);
2431                 p->dialing = 0;
2432                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2433                         if (oldstate == AST_STATE_RINGING) {
2434                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2435                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2436                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2437                                 p->owner = p->subs[SUB_REAL].owner;
2438                         }
2439                 }
2440                 if (p->sig & __ZT_SIG_FXS) {
2441                         zt_enable_ec(p);
2442                         zt_train_ec(p);
2443                 }
2444                 break;
2445 #ifdef ZAPATA_PRI
2446         case SIG_PRI:
2447                 /* Send a pri acknowledge */
2448                 if (!pri_grab(p, p->pri)) {
2449                         p->proceeding = 2;
2450                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2451                         pri_rel(p->pri);
2452                 } else {
2453                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2454                         res= -1;
2455                 }
2456                 break;
2457 #endif
2458 #ifdef ZAPATA_R2
2459         case SIG_R2:
2460                 res = mfcr2_AnswerCall(p->r2, NULL);
2461                 if (res)
2462                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2463                 break;
2464 #endif                  
2465         case 0:
2466                 ast_mutex_unlock(&p->lock);
2467                 return 0;
2468         default:
2469                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2470                 res = -1;
2471         }
2472         ast_mutex_unlock(&p->lock);
2473         return res;
2474 }
2475
2476 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2477 {
2478 char    *cp;
2479 int     x;
2480
2481         struct zt_pvt *p = chan->tech_pvt;
2482
2483         
2484         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2485                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2486            {
2487                 errno = ENOSYS;
2488                 return -1;
2489            }
2490         cp = (char *)data;
2491         if ((!cp) || (datalen < 1))
2492            {
2493                 errno = EINVAL;
2494                 return -1;
2495            }
2496         switch(option) {
2497             case AST_OPTION_TONE_VERIFY:
2498                 if (!p->dsp)
2499                         break;
2500                 switch(*cp) {
2501                     case 1:
2502                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2503                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2504                         break;
2505                     case 2:
2506                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2507                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2508                         break;
2509                     default:
2510                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2511                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2512                         break;
2513                 }
2514                 break;
2515             case AST_OPTION_TDD:  /* turn on or off TDD */
2516                 if (!*cp) { /* turn it off */
2517                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2518                         if (p->tdd) tdd_free(p->tdd);
2519                         p->tdd = 0;
2520                         p->mate = 0;
2521                         break;
2522                 }
2523                 if (*cp == 2)
2524                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2525                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2526                 p->mate = 0;
2527                 zt_disable_ec(p);
2528                 /* otherwise, turn it on */
2529                 if (!p->didtdd) { /* if havent done it yet */
2530                         unsigned char mybuf[41000],*buf;
2531                         int size,res,fd,len;
2532                         int index;
2533                         struct pollfd fds[1];
2534                         buf = mybuf;
2535                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2536                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2537                         len = 40000;
2538                         index = zt_get_index(chan, p, 0);
2539                         if (index < 0) {
2540                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2541                                 return -1;
2542                         }
2543                         fd = p->subs[index].zfd;
2544                         while(len) {
2545                                 if (ast_check_hangup(chan)) return -1;
2546                                 size = len;
2547                                 if (size > READ_SIZE)
2548                                         size = READ_SIZE;
2549                                 fds[0].fd = fd;
2550                                 fds[0].events = POLLPRI | POLLOUT;
2551                                 res = poll(fds, 1, -1);
2552                                 if (!res) {
2553                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2554                                         continue;
2555                                 }
2556                                   /* if got exception */
2557                                 if (fds[0].revents & POLLPRI) return -1;
2558                                 if (!(fds[0].revents & POLLOUT)) {
2559                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2560                                         continue;
2561                                 }
2562                                 res = write(fd, buf, size);
2563                                 if (res != size) {
2564                                         if (res == -1) return -1;
2565                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2566                                         break;
2567                                 }
2568                                 len -= size;
2569                                 buf += size;
2570                         }
2571                         p->didtdd = 1; /* set to have done it now */            
2572                 }
2573                 if (*cp == 2) { /* Mate mode */
2574                         if (p->tdd) tdd_free(p->tdd);
2575                         p->tdd = 0;
2576                         p->mate = 1;
2577                         break;
2578                         }               
2579                 if (!p->tdd) { /* if we dont have one yet */
2580                         p->tdd = tdd_new(); /* allocate one */
2581                 }               
2582                 break;
2583             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2584                 if (!*cp)
2585                 {               
2586                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2587                         x = 0;
2588                 }
2589                 else
2590                 {               
2591                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2592                         x = 1;
2593                 }
2594                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2595                 break;
2596             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2597                 if (!*cp)
2598                 {               
2599                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2600                         x = 0;
2601                         zt_disable_ec(p);
2602                 }
2603                 else
2604                 {               
2605                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2606                         x = 1;
2607                 }
2608                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2609                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2610                 break;
2611         }
2612         errno = 0;
2613         return 0;
2614 }
2615
2616 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2617 {
2618         /* Unlink a specific slave or all slaves/masters from a given master */
2619         int x;
2620         int hasslaves;
2621         if (!master)
2622                 return;
2623         if (needlock) {
2624                 ast_mutex_lock(&master->lock);
2625                 if (slave) {
2626                         while(ast_mutex_trylock(&slave->lock)) {
2627                                 ast_mutex_unlock(&master->lock);
2628                                 usleep(1);
2629                                 ast_mutex_lock(&master->lock);
2630                         }
2631                 }
2632         }
2633         hasslaves = 0;
2634         for (x=0;x<MAX_SLAVES;x++) {
2635                 if (master->slaves[x]) {
2636                         if (!slave || (master->slaves[x] == slave)) {
2637                                 /* Take slave out of the conference */
2638                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2639                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2640                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2641                                 master->slaves[x]->master = NULL;
2642                                 master->slaves[x] = NULL;
2643                         } else
2644                                 hasslaves = 1;
2645                 }
2646                 if (!hasslaves)
2647                         master->inconference = 0;
2648         }
2649         if (!slave) {
2650                 if (master->master) {
2651                         /* Take master out of the conference */
2652                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2653                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2654                         hasslaves = 0;
2655                         for (x=0;x<MAX_SLAVES;x++) {
2656                                 if (master->master->slaves[x] == master)
2657                                         master->master->slaves[x] = NULL;
2658                                 else if (master->master->slaves[x])
2659                                         hasslaves = 1;
2660                         }
2661                         if (!hasslaves)
2662                                 master->master->inconference = 0;
2663                 }
2664                 master->master = NULL;
2665         }
2666         update_conf(master);
2667         if (needlock) {
2668                 if (slave)
2669                         ast_mutex_unlock(&slave->lock);
2670                 ast_mutex_unlock(&master->lock);
2671         }
2672 }
2673
2674 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2675         int x;
2676         if (!slave || !master) {
2677                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2678                 return;
2679         }
2680         for (x=0;x<MAX_SLAVES;x++) {
2681                 if (!master->slaves[x]) {
2682                         master->slaves[x] = slave;
2683                         break;
2684                 }
2685         }
2686         if (x >= MAX_SLAVES) {
2687                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2688                 master->slaves[MAX_SLAVES - 1] = slave;
2689         }
2690         if (slave->master) 
2691                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2692         slave->master = master;
2693         
2694         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2695 }
2696
2697 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2698 {
2699         struct ast_channel *who = NULL, *cs[3];
2700         struct zt_pvt *p0, *p1, *op0, *op1;
2701         struct zt_pvt *master=NULL, *slave=NULL;
2702         struct ast_frame *f;
2703         int to;
2704         int inconf = 0;
2705         int nothingok = 0;
2706         int ofd1, ofd2;
2707         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2708         int os1 = -1, os2 = -1;
2709         struct ast_channel *oc1, *oc2;
2710 #ifdef PRI_2BCT
2711         int triedtopribridge = 0;
2712         q931_call *q931c0 = NULL, *q931c1 = NULL;
2713 #endif
2714
2715
2716         /* if need DTMF, cant native bridge */
2717         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2718                 return -2;
2719                 
2720         ast_mutex_lock(&c0->lock);
2721         ast_mutex_lock(&c1->lock);
2722
2723         p0 = c0->tech_pvt;
2724         p1 = c1->tech_pvt;
2725         /* cant do pseudo-channels here */
2726         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2727                 ast_mutex_unlock(&c0->lock);
2728                 ast_mutex_unlock(&c1->lock);
2729                 return -2;
2730         }
2731
2732         op0 = p0 = c0->tech_pvt;
2733         op1 = p1 = c1->tech_pvt;
2734         ofd1 = c0->fds[0];
2735         ofd2 = c1->fds[0];
2736         oi1 = zt_get_index(c0, p0, 0);
2737         oi2 = zt_get_index(c1, p1, 0);
2738         oc1 = p0->owner;
2739         oc2 = p1->owner;
2740         if ((oi1 < 0) || (oi2 < 0)) {
2741                 ast_mutex_unlock(&c0->lock);
2742                 ast_mutex_unlock(&c1->lock);
2743                 return -1;
2744         }
2745
2746
2747
2748         ast_mutex_lock(&p0->lock);
2749         if (ast_mutex_trylock(&p1->lock)) {
2750                 /* Don't block, due to potential for deadlock */
2751                 ast_mutex_unlock(&p0->lock);
2752                 ast_mutex_unlock(&c0->lock);
2753                 ast_mutex_unlock(&c1->lock);
2754                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2755                 return -3;
2756         }
2757         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2758                 if (!p0->owner || !p1->owner) {
2759                         /* Currently unowned -- Do nothing.  */
2760                         nothingok = 1;
2761                 } else {
2762                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2763                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2764                                 master = p0;
2765                                 slave = p1;
2766                                 inconf = 1;
2767                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2768                                 master = p1;
2769                                 slave = p0;
2770                                 inconf = 1;
2771                         } else {
2772                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2773                                 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,
2774                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2775                         }
2776                 }
2777         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2778                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2779                         master = p1;
2780                         slave = p0;
2781                 } else {
2782                         nothingok = 1;
2783                 }
2784         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2785                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2786                         master = p0;
2787                         slave = p1;
2788                 } else {
2789                         nothingok  = 1;
2790                 }
2791         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2792                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2793                    don't put us in anything */
2794                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2795                         master = p1;
2796                         slave = p0;
2797                 } else {
2798                         nothingok = 1;
2799                 }
2800         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2801                 /* Same as previous */
2802                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2803                         master = p0;
2804                         slave = p1;
2805                 } else {
2806                         nothingok = 1;
2807                 }
2808         }
2809         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2810                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2811         if (master && slave) {
2812                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2813                    in an active threeway call with a channel that is ringing, we should
2814                    indicate ringing. */
2815                 if ((oi2 == SUB_THREEWAY) && 
2816                         p1->subs[SUB_THREEWAY].inthreeway && 
2817                         p1->subs[SUB_REAL].owner && 
2818                         p1->subs[SUB_REAL].inthreeway && 
2819                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2820                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2821                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2822                                 os2 = p1->subs[SUB_REAL].owner->_state;
2823                 } else {
2824                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2825                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2826                 }
2827                 if ((oi1 == SUB_THREEWAY) && 
2828                         p0->subs[SUB_THREEWAY].inthreeway && 
2829                         p0->subs[SUB_REAL].owner && 
2830                         p0->subs[SUB_REAL].inthreeway && 
2831                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2832                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2833                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2834                                 os1 = p0->subs[SUB_REAL].owner->_state;
2835                 } else {
2836                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2837                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2838                 }
2839                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2840                         if (!p0->echocanbridged || !p1->echocanbridged) {
2841                                 /* Disable echo cancellation if appropriate */
2842                                 zt_disable_ec(p0);
2843                                 zt_disable_ec(p1);
2844                         }
2845                 }
2846                 zt_link(slave, master);
2847                 master->inconference = inconf;
2848         } else if (!nothingok)
2849                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2850
2851         update_conf(p0);
2852         update_conf(p1);
2853         t1 = p0->subs[SUB_REAL].inthreeway;
2854         t2 = p1->subs[SUB_REAL].inthreeway;
2855
2856         ast_mutex_unlock(&p0->lock);
2857         ast_mutex_unlock(&p1->lock);
2858
2859         ast_mutex_unlock(&c0->lock);
2860         ast_mutex_unlock(&c1->lock);
2861
2862         /* Native bridge failed */
2863         if ((!master || !slave) && !nothingok) {
2864                 if (op0 == p0)
2865                         zt_enable_ec(p0);
2866                 if (op1 == p1)
2867                         zt_enable_ec(p1);
2868                 return -1;
2869         }
2870         
2871         cs[0] = c0;
2872         cs[1] = c1;
2873         cs[2] = NULL;
2874         for (;;) {
2875                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2876                    and then balking if anything is wrong */
2877                 ast_mutex_lock(&c0->lock);
2878                 ast_mutex_lock(&c1->lock);
2879                 p0 = c0->tech_pvt;
2880                 p1 = c1->tech_pvt;
2881
2882 #ifdef PRI_2BCT
2883                 q931c0 = p0->call;
2884                 q931c1 = p1->call;
2885                 if (p0->transfer && p1->transfer 
2886                                 && q931c0 && q931c1 
2887                                 && !triedtopribridge) {
2888
2889                         pri_channel_bridge(q931c0, q931c1);
2890                         triedtopribridge = 1;
2891                 }
2892 #endif
2893                 if (op0 == p0)
2894                         i1 = zt_get_index(c0, p0, 1);
2895                 if (op1 == p1)
2896                         i2 = zt_get_index(c1, p1, 1);
2897                 ast_mutex_unlock(&c0->lock);
2898                 ast_mutex_unlock(&c1->lock);
2899                 if ((op0 != p0) || (op1 != p1) || 
2900                     (ofd1 != c0->fds[0]) || 
2901                         (ofd2 != c1->fds[0]) ||
2902                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2903                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2904                     (oc1 != p0->owner) || 
2905                         (oc2 != p1->owner) ||
2906                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2907                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2908                         (oi1 != i1) ||
2909                         (oi2 != i2)) {
2910                         if (slave && master)
2911                                 zt_unlink(slave, master, 1);
2912                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2913                                                                         op0->channel, oi1, op1->channel, oi2);
2914                         if (op0 == p0)
2915                                 zt_enable_ec(p0);
2916                         if (op1 == p1)
2917                                 zt_enable_ec(p1);
2918                         return -3;
2919                 }
2920                 to = -1;
2921                 who = ast_waitfor_n(cs, 2, &to);
2922                 if (!who) {
2923                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2924                         continue;
2925                 }
2926                 if (who->tech_pvt == op0) 
2927                         op0->ignoredtmf = 1;
2928                 else if (who->tech_pvt == op1)
2929                         op1->ignoredtmf = 1;
2930                 f = ast_read(who);
2931                 if (who->tech_pvt == op0) 
2932                         op0->ignoredtmf = 0;
2933                 else if (who->tech_pvt == op1)
2934                         op1->ignoredtmf = 0;
2935                 if (!f) {
2936                         *fo = NULL;
2937                         *rc = who;
2938                         if (slave && master)
2939                                 zt_unlink(slave, master, 1);
2940                         if (op0 == p0)
2941                                 zt_enable_ec(p0);
2942                         if (op1 == p1)
2943                                 zt_enable_ec(p1);
2944                         return 0;
2945                 }
2946                 if (f->frametype == AST_FRAME_CONTROL) {
2947                         *fo = f;
2948                         *rc = who;
2949                         if (slave && master)
2950                                 zt_unlink(slave, master, 1);
2951                         return 0;
2952                 }
2953                 if (f->frametype == AST_FRAME_DTMF) {
2954                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2955                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2956                                 *fo = f;
2957                                 *rc = who;
2958                                 if (slave && master)
2959                                         zt_unlink(slave, master, 1);
2960                                 return 0;
2961                         } else if ((who == c0) && p0->pulsedial) {
2962                                 ast_write(c1, f);
2963                         } else if ((who == c1) && p1->pulsedial) {
2964                                 ast_write(c0, f);
2965                         }
2966                 }
2967                 ast_frfree(f);
2968
2969                 /* Swap who gets priority */
2970                 cs[2] = cs[0];
2971                 cs[0] = cs[1];
2972                 cs[1] = cs[2];
2973         }
2974 }
2975
2976 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2977 {
2978         struct zt_pvt *p = newchan->tech_pvt;
2979         int x;
2980         ast_mutex_lock(&p->lock);
2981         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2982         if (p->owner == oldchan) {
2983                 p->owner = newchan;
2984         }
2985         for (x=0;x<3;x++)
2986                 if (p->subs[x].owner == oldchan) {
2987                         if (!x)
2988                                 zt_unlink(NULL, p, 0);
2989                         p->subs[x].owner = newchan;
2990                 }