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