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