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