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