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