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