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