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