eb4cc05008a455cfa675136b7be682ae26a3e273
[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)
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         hasslaves = 0;
2207         for (x=0;x<MAX_SLAVES;x++) {
2208                 if (master->slaves[x]) {
2209                         if (!slave || (master->slaves[x] == slave)) {
2210                                 /* Take slave out of the conference */
2211                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2212                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2213                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2214                                 master->slaves[x]->master = NULL;
2215                                 master->slaves[x] = NULL;
2216                         } else
2217                                 hasslaves = 1;
2218                 }
2219                 if (!hasslaves)
2220                         master->inconference = 0;
2221         }
2222         if (!slave) {
2223                 if (master->master) {
2224                         /* Take master out of the conference */
2225                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2226                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2227                         hasslaves = 0;
2228                         for (x=0;x<MAX_SLAVES;x++) {
2229                                 if (master->master->slaves[x] == master)
2230                                         master->master->slaves[x] = NULL;
2231                                 else if (master->master->slaves[x])
2232                                         hasslaves = 1;
2233                         }
2234                         if (!hasslaves)
2235                                 master->master->inconference = 0;
2236                 }
2237                 master->master = NULL;
2238         }
2239         update_conf(master);
2240 }
2241
2242 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2243         int x;
2244         if (!slave || !master) {
2245                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2246                 return;
2247         }
2248         for (x=0;x<MAX_SLAVES;x++) {
2249                 if (!master->slaves[x]) {
2250                         master->slaves[x] = slave;
2251                         break;
2252                 }
2253         }
2254         if (x >= MAX_SLAVES) {
2255                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2256                 master->slaves[MAX_SLAVES - 1] = slave;
2257         }
2258         if (slave->master) 
2259                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2260         slave->master = master;
2261         
2262         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2263 }
2264
2265 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2266 {
2267         struct ast_channel *who = NULL, *cs[3];
2268         struct zt_pvt *p0, *p1, *op0, *op1;
2269         struct zt_pvt *master=NULL, *slave=NULL;
2270         struct ast_frame *f;
2271         int to;
2272         int inconf = 0;
2273         int nothingok = 0;
2274         int ofd1, ofd2;
2275         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2276         int os1 = -1, os2 = -1;
2277         struct ast_channel *oc1, *oc2;
2278
2279         /* if need DTMF, cant native bridge */
2280         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2281                 return -2;
2282                 
2283         ast_mutex_lock(&c0->lock);
2284         ast_mutex_lock(&c1->lock);
2285
2286         p0 = c0->pvt->pvt;
2287         p1 = c1->pvt->pvt;
2288         /* cant do pseudo-channels here */
2289         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2290                 ast_mutex_unlock(&c0->lock);
2291                 ast_mutex_unlock(&c1->lock);
2292                 return -2;
2293         }
2294
2295         op0 = p0 = c0->pvt->pvt;
2296         op1 = p1 = c1->pvt->pvt;
2297         ofd1 = c0->fds[0];
2298         ofd2 = c1->fds[0];
2299         oi1 = zt_get_index(c0, p0, 0);
2300         oi2 = zt_get_index(c1, p1, 0);
2301         oc1 = p0->owner;
2302         oc2 = p1->owner;
2303         if ((oi1 < 0) || (oi2 < 0))
2304                 return -1;
2305
2306
2307
2308         ast_mutex_lock(&p0->lock);
2309         if (ast_mutex_trylock(&p1->lock)) {
2310                 /* Don't block, due to potential for deadlock */
2311                 ast_mutex_unlock(&p0->lock);
2312                 ast_mutex_unlock(&c0->lock);
2313                 ast_mutex_unlock(&c1->lock);
2314                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2315                 return -3;
2316         }
2317         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2318                 if (!p0->owner || !p1->owner) {
2319                         /* Currently unowned -- Do nothing.  */
2320                         nothingok = 1;
2321                 } else {
2322                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2323                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2324                                 master = p0;
2325                                 slave = p1;
2326                                 inconf = 1;
2327                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2328                                 master = p1;
2329                                 slave = p0;
2330                                 inconf = 1;
2331                         } else {
2332                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2333                                 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,
2334                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2335                         }
2336                 }
2337         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2338                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2339                         master = p1;
2340                         slave = p0;
2341                 } else {
2342                         nothingok = 1;
2343                 }
2344         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2345                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2346                         master = p0;
2347                         slave = p1;
2348                 } else {
2349                         nothingok  = 1;
2350                 }
2351         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2352                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2353                    don't put us in anything */
2354                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2355                         master = p1;
2356                         slave = p0;
2357                 } else {
2358                         nothingok = 1;
2359                 }
2360         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2361                 /* Same as previous */
2362                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2363                         master = p0;
2364                         slave = p1;
2365                 } else {
2366                         nothingok = 1;
2367                 }
2368         }
2369         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2370                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2371         if (master && slave) {
2372                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2373                    in an active threeway call with a channel that is ringing, we should
2374                    indicate ringing. */
2375                 if ((oi2 == SUB_THREEWAY) && 
2376                         p1->subs[SUB_THREEWAY].inthreeway && 
2377                         p1->subs[SUB_REAL].owner && 
2378                         p1->subs[SUB_REAL].inthreeway && 
2379                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2380                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2381                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2382                                 os2 = p1->subs[SUB_REAL].owner->_state;
2383                 } else {
2384                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2385                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2386                 }
2387                 if ((oi1 == SUB_THREEWAY) && 
2388                         p0->subs[SUB_THREEWAY].inthreeway && 
2389                         p0->subs[SUB_REAL].owner && 
2390                         p0->subs[SUB_REAL].inthreeway && 
2391                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2392                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2393                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2394                                 os1 = p0->subs[SUB_REAL].owner->_state;
2395                 } else {
2396                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2397                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2398                 }
2399                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2400                         if (!p0->echocanbridged || !p1->echocanbridged) {
2401                                 /* Disable echo cancellation if appropriate */
2402                                 zt_disable_ec(p0);
2403                                 zt_disable_ec(p1);
2404                         }
2405                 }
2406                 zt_link(slave, master);
2407                 master->inconference = inconf;
2408         } else if (!nothingok)
2409                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2410
2411         update_conf(p0);
2412         update_conf(p1);
2413         t1 = p0->subs[SUB_REAL].inthreeway;
2414         t2 = p1->subs[SUB_REAL].inthreeway;
2415
2416         ast_mutex_unlock(&p0->lock);
2417         ast_mutex_unlock(&p1->lock);
2418
2419         ast_mutex_unlock(&c0->lock);
2420         ast_mutex_unlock(&c1->lock);
2421
2422         /* Native bridge failed */
2423         if ((!master || !slave) && !nothingok) {
2424                 if (op0 == p0)
2425                         zt_enable_ec(p0);
2426                 if (op1 == p1)
2427                         zt_enable_ec(p1);
2428                 return -1;
2429         }
2430         
2431         cs[0] = c0;
2432         cs[1] = c1;
2433         cs[2] = NULL;
2434         for (;;) {
2435                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2436                    and then balking if anything is wrong */
2437                 ast_mutex_lock(&c0->lock);
2438                 ast_mutex_lock(&c1->lock);
2439                 p0 = c0->pvt->pvt;
2440                 p1 = c1->pvt->pvt;
2441                 if (op0 == p0)
2442                         i1 = zt_get_index(c0, p0, 1);
2443                 if (op1 == p1)
2444                         i2 = zt_get_index(c1, p1, 1);
2445                 ast_mutex_unlock(&c0->lock);
2446                 ast_mutex_unlock(&c1->lock);
2447                 if ((op0 != p0) || (op1 != p1) || 
2448                     (ofd1 != c0->fds[0]) || 
2449                         (ofd2 != c1->fds[0]) ||
2450                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2451                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2452                     (oc1 != p0->owner) || 
2453                         (oc2 != p1->owner) ||
2454                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2455                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2456                         (oi1 != i1) ||
2457                         (oi2 != i2)) {
2458                         if (slave && master)
2459                                 zt_unlink(slave, master);
2460                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2461                                                                         op0->channel, oi1, op1->channel, oi2);
2462                         if (op0 == p0)
2463                                 zt_enable_ec(p0);
2464                         if (op1 == p1)
2465                                 zt_enable_ec(p1);
2466                         return -3;
2467                 }
2468                 to = -1;
2469                 who = ast_waitfor_n(cs, 2, &to);
2470                 if (!who) {
2471                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2472                         continue;
2473                 }
2474                 if (who->pvt->pvt == op0) 
2475                         op0->ignoredtmf = 1;
2476                 else if (who->pvt->pvt == op1)
2477                         op1->ignoredtmf = 1;
2478                 f = ast_read(who);
2479                 if (who->pvt->pvt == op0) 
2480                         op0->ignoredtmf = 0;
2481                 else if (who->pvt->pvt == op1)
2482                         op1->ignoredtmf = 0;
2483                 if (!f) {
2484                         *fo = NULL;
2485                         *rc = who;
2486                         if (slave && master)
2487                                 zt_unlink(slave, master);
2488                         if (op0 == p0)
2489                                 zt_enable_ec(p0);
2490                         if (op1 == p1)
2491                                 zt_enable_ec(p1);
2492                         return 0;
2493                 }
2494                 if (f->frametype == AST_FRAME_DTMF) {
2495                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2496                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2497                                 *fo = f;
2498                                 *rc = who;
2499                                 if (slave && master)
2500                                         zt_unlink(slave, master);
2501                                 return 0;
2502                         } else if ((who == c0) && p0->pulsedial) {
2503                                 ast_write(c1, f);
2504                         } else if ((who == c1) && p1->pulsedial) {
2505                                 ast_write(c0, f);
2506                         }
2507                 }
2508                 ast_frfree(f);
2509
2510                 /* Swap who gets priority */
2511                 cs[2] = cs[0];
2512                 cs[0] = cs[1];
2513                 cs[1] = cs[2];
2514         }
2515 }
2516
2517 static int zt_indicate(struct ast_channel *chan, int condition);
2518
2519 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2520 {
2521         struct zt_pvt *p = newchan->pvt->pvt;
2522         int x;
2523         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2524         if (p->owner == oldchan)
2525                 p->owner = newchan;
2526         for (x=0;x<3;x++)
2527                 if (p->subs[x].owner == oldchan) {
2528                         if (!x)
2529                                 zt_unlink(NULL, p);
2530                         p->subs[x].owner = newchan;
2531                 }
2532         if (newchan->_state == AST_STATE_RINGING) 
2533                 zt_indicate(newchan, AST_CONTROL_RINGING);
2534         update_conf(p);
2535         return 0;
2536 }
2537
2538 static int zt_ring_phone(struct zt_pvt *p)
2539 {
2540         int x;
2541         int res;
2542         /* Make sure our transmit state is on hook */
2543         x = 0;
2544         x = ZT_ONHOOK;
2545         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2546         do {
2547                 x = ZT_RING;
2548                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2549 #if 0
2550                 printf("Res: %d, error: %s\n", res, strerror(errno));
2551 #endif                                          
2552                 if (res) {
2553                         switch(errno) {
2554                         case EBUSY:
2555                         case EINTR:
2556                                 /* Wait just in case */
2557                                 usleep(10000);
2558                                 continue;
2559                         case EINPROGRESS:
2560                                 res = 0;
2561                                 break;
2562                         default:
2563                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2564                                 res = 0;
2565                         }
2566                 }
2567         } while (res);
2568         return res;
2569 }
2570
2571 static void *ss_thread(void *data);
2572
2573 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2574
2575 static int attempt_transfer(struct zt_pvt *p)
2576 {
2577         /* In order to transfer, we need at least one of the channels to
2578            actually be in a call bridge.  We can't conference two applications
2579            together (but then, why would we want to?) */
2580         if (p->subs[SUB_REAL].owner->bridge) {
2581                 /* The three-way person we're about to transfer to could still be in MOH, so
2582                    stop if now if appropriate */
2583                 if (p->subs[SUB_THREEWAY].owner->bridge)
2584                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2585                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2586                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2587                 }
2588                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2589                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2590                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2591                         return -1;
2592                 }
2593                 /* Orphan the channel */
2594                 unalloc_sub(p, SUB_THREEWAY);
2595         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2596                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2597                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2598                 }
2599                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2600                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2601                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2602                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2603                         return -1;
2604                 }
2605                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2606                 unalloc_sub(p, SUB_THREEWAY);
2607                 /* Tell the caller not to hangup */
2608                 return 1;
2609         } else {
2610                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2611                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2612                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2613         }
2614         return 0;
2615 }
2616
2617 #ifdef ZAPATA_R2
2618 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2619 {
2620         struct ast_frame *f;
2621         f = &p->subs[index].f;
2622         if (!p->r2) {
2623                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2624                 return NULL;
2625         }
2626         switch(e->e) {
2627         case MFCR2_EVENT_BLOCKED:
2628                 if (option_verbose > 2)
2629                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2630                 break;
2631         case MFCR2_EVENT_UNBLOCKED:
2632                 if (option_verbose > 2)
2633                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2634                 break;
2635         case MFCR2_EVENT_CONFIG_ERR:
2636                 if (option_verbose > 2)
2637                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2638                 break;
2639         case MFCR2_EVENT_RING:
2640                 if (option_verbose > 2)
2641                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2642                 break;
2643         case MFCR2_EVENT_HANGUP:
2644                 if (option_verbose > 2)
2645                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2646                 break;
2647         case MFCR2_EVENT_RINGING:
2648                 if (option_verbose > 2)
2649                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2650                 break;
2651         case MFCR2_EVENT_ANSWER:
2652                 if (option_verbose > 2)
2653                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2654                 break;
2655         case MFCR2_EVENT_HANGUP_ACK:
2656                 if (option_verbose > 2)
2657                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2658                 break;
2659         case MFCR2_EVENT_IDLE:
2660                 if (option_verbose > 2)
2661                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2662                 break;
2663         default:
2664                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2665                 break;
2666         }
2667         return f;
2668 }
2669
2670 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2671 {
2672         int x;
2673         int res;
2674         mfcr2_event_t *e;
2675         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2676         if (res) {
2677                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2678                 return NULL;
2679         }
2680         if (!p->r2) {
2681                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2682                 return NULL;
2683         }
2684         e = mfcr2_cas_signaling_event(p->r2, x);
2685         return e;
2686 }
2687 #endif
2688
2689 static int check_for_conference(struct zt_pvt *p)
2690 {
2691         ZT_CONFINFO ci;
2692         /* Fine if we already have a master, etc */
2693         if (p->master || (p->confno > -1))
2694                 return 0;
2695         memset(&ci, 0, sizeof(ci));
2696         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2697                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2698                 return 0;
2699         }
2700         /* If we have no master and don't have a confno, then 
2701            if we're in a conference, it's probably a MeetMe room or
2702            some such, so don't let us 3-way out! */
2703         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
2704                 if (option_verbose > 2) 
2705                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2706                 return 1;
2707         }
2708         return 0;
2709 }
2710
2711 static int get_alarms(struct zt_pvt *p)
2712 {
2713         int res;
2714         ZT_SPANINFO zi;
2715         memset(&zi, 0, sizeof(zi));
2716         zi.spanno = p->span;
2717         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2718         if (res < 0) {
2719                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2720                 return 0;
2721         }
2722         return zi.alarms;
2723 }
2724                         
2725 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2726 {
2727         int res,x;
2728         int index;
2729         char *c;
2730         struct zt_pvt *p = ast->pvt->pvt;
2731         pthread_t threadid;
2732         pthread_attr_t attr;
2733         struct ast_channel *chan;
2734         pthread_attr_init(&attr);
2735         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2736         index = zt_get_index(ast, p, 0);
2737         p->subs[index].f.frametype = AST_FRAME_NULL;
2738         p->subs[index].f.datalen = 0;
2739         p->subs[index].f.samples = 0;
2740         p->subs[index].f.mallocd = 0;
2741         p->subs[index].f.offset = 0;
2742         p->subs[index].f.src = "zt_handle_event";
2743         p->subs[index].f.data = NULL;
2744         if (index < 0)
2745                 return &p->subs[index].f;
2746         if (p->fake_event) {
2747                 res = p->fake_event;
2748                 p->fake_event = 0;
2749         } else
2750                 res = zt_get_event(p->subs[index].zfd);
2751         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
2752         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFDIGIT)) {
2753                 if (res & ZT_EVENT_PULSEDIGIT)
2754                         p->pulsedial = 1;
2755                 else
2756                         p->pulsedial = 0;
2757                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
2758                 p->subs[index].f.frametype = AST_FRAME_DTMF;
2759                 p->subs[index].f.subclass = res & 0xff;
2760                 /* Return the captured digit */
2761                 return &p->subs[index].f;
2762         }
2763         switch(res) {
2764                 case ZT_EVENT_BITSCHANGED:
2765                         if (p->sig == SIG_R2) {
2766 #ifdef ZAPATA_R2
2767                                 struct ast_frame  *f = &p->subs[index].f;
2768                                 mfcr2_event_t *e;
2769                                 e = r2_get_event_bits(p);
2770                                 if (e)
2771                                         f = handle_r2_event(p, e, index);
2772                                 return f;
2773 #else                           
2774                                 break;
2775 #endif
2776                         }
2777                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
2778                 case ZT_EVENT_PULSE_START:
2779                         /* Stop tone if there's a pulse start and the PBX isn't started */
2780                         if (!ast->pbx)
2781                                 tone_zone_play_tone(p->subs[index].zfd, -1);
2782                         break;  
2783                 case ZT_EVENT_DIALCOMPLETE:
2784                         if (p->inalarm) break;
2785                         if (p->radio) break;
2786                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
2787                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
2788                                 return NULL;
2789                         }
2790                         if (!x) { /* if not still dialing in driver */
2791                                 zt_enable_ec(p);
2792                                 if (p->echobreak) {
2793                                         zt_train_ec(p);
2794                                         strcpy(p->dop.dialstr, p->echorest);
2795                                         p->dop.op = ZT_DIAL_OP_REPLACE;
2796                                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2797                                         p->echobreak = 0;
2798                                 } else {
2799                                         p->dialing = 0;
2800                                         if (p->sig == SIG_E911) {
2801                                                 /* if thru with dialing after offhook */
2802                                                 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2803                                                         ast_setstate(ast, AST_STATE_UP);
2804                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2805                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2806                                                         break;
2807                                                 } else { /* if to state wait for offhook to dial rest */
2808                                                         /* we now wait for off hook */
2809                                                         ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2810                                                 }
2811                                         }
2812                                         if (ast->_state == AST_STATE_DIALING) {
2813                                                 if (p->callprogress && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
2814                                                         ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
2815                                                 } 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)))) {
2816                                                         ast_setstate(ast, AST_STATE_RINGING);
2817                                                 } else {
2818                                                         ast_setstate(ast, AST_STATE_UP);
2819                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2820                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2821                                                 }
2822                                         }
2823                                 }
2824                         }
2825                         break;
2826                 case ZT_EVENT_ALARM:
2827 #ifdef ZAPATA_PRI
2828 #ifdef PRI_DESTROYCALL
2829                         if (p->call) {
2830                                 if (p->pri && p->pri->pri) {
2831                                         pri_hangup(p->pri->pri, p->call, -1);
2832                                         pri_destroycall(p->pri->pri, p->call);
2833                                 } else
2834                                         ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2835                         }
2836                         if (p->owner)
2837                                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2838                         p->call = NULL;
2839 #else
2840 #error Please "cvs update" and recompile libpri
2841 #endif
2842 #endif
2843                         p->inalarm = 1;
2844                         res = get_alarms(p);
2845                         ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
2846                         manager_event(EVENT_FLAG_SYSTEM, "Alarm",
2847                                                                 "Alarm: %s\r\n"
2848                                                                 "Channel: %d\r\n",
2849                                                                 alarm2str(res), p->channel);
2850                         /* fall through intentionally */
2851                 case ZT_EVENT_ONHOOK:
2852                         if (p->radio)
2853                         {
2854                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2855                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
2856                                 break;
2857                         }
2858                         switch(p->sig) {
2859                         case SIG_FXOLS:
2860                         case SIG_FXOGS:
2861                         case SIG_FXOKS:
2862                                 p->onhooktime = time(NULL);
2863                                 p->msgstate = -1;
2864                                 /* Check for some special conditions regarding call waiting */
2865                                 if (index == SUB_REAL) {
2866                                         /* The normal line was hung up */
2867                                         if (p->subs[SUB_CALLWAIT].owner) {
2868                                                 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2869                                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2870                                                 if (option_verbose > 2) 
2871                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2872                                                 unalloc_sub(p, SUB_CALLWAIT);   
2873 #if 0
2874                                                 p->subs[index].needanswer = 0;
2875                                                 p->subs[index].needringing = 0;
2876 #endif                                          
2877                                                 p->callwaitingrepeat = 0;
2878                                                 p->cidcwexpire = 0;
2879                                                 p->owner = NULL;
2880                                                 zt_ring_phone(p);
2881                                         } else if (p->subs[SUB_THREEWAY].owner) {
2882                                                 struct timeval tv;
2883                                                 unsigned int mssinceflash;
2884                                                 gettimeofday(&tv, NULL);
2885                                                 mssinceflash = (tv.tv_sec - p->flashtime.tv_sec) * 1000 + (tv.tv_usec - p->flashtime.tv_usec) / 1000;
2886                                                 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
2887                                                 if (mssinceflash < MIN_MS_SINCE_FLASH) {
2888                                                         /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
2889                                                            hanging up.  Hangup both channels now */
2890                                                         if (p->subs[SUB_THREEWAY].owner)
2891                                                                 ast_queue_hangup(p->subs[SUB_THREEWAY].owner, 0);
2892                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2893                                                         ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2894                                                 } else if ((ast->pbx) ||
2895                                                         (ast->_state == AST_STATE_UP)) {
2896                                                         if (p->transfer) {
2897                                                                 /* In any case this isn't a threeway call anymore */
2898                                                                 p->subs[SUB_REAL].inthreeway = 0;
2899                                                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2900                                                                 if ((res = attempt_transfer(p)) < 0)
2901                                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2902                                                                 else if (res) {
2903                                                                         /* Don't actually hang up at this point */
2904                                                                         break;
2905                                                                 }
2906                                                         } else
2907                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2908                                                 } else {
2909                                                         /* Swap subs and dis-own channel */
2910                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2911                                                         p->owner = NULL;
2912                                                         /* Ring the phone */
2913                                                         zt_ring_phone(p);
2914                                                 }
2915                                         }
2916                                 } else {
2917                                         ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
2918                                 }
2919                                 /* Fall through */
2920                         default:
2921                                 zt_disable_ec(p);
2922                                 return NULL;
2923                         }
2924                         break;
2925                 case ZT_EVENT_RINGOFFHOOK:
2926                         if (p->inalarm) break;
2927                         if (p->radio)
2928                         {
2929                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2930                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
2931                                 break;
2932                         }
2933                         /* for E911, its supposed to wait for offhook then dial
2934                            the second half of the dial string */
2935                         if ((p->sig == SIG_E911) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
2936                                 c = strchr(p->dialdest, '/');
2937                                 if (c)
2938                                         c++;
2939                                 else
2940                                         c = p->dialdest;
2941                                 if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
2942                                 else strcpy(p->dop.dialstr,"M*2#");
2943                                 if (strlen(p->dop.dialstr) > 4) {
2944                                         strcpy(p->echorest, "w");
2945                                         strcpy(p->echorest + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2946                                         p->echobreak = 1;
2947                                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2948                                 } else
2949                                         p->echobreak = 0;
2950                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
2951                                         x = ZT_ONHOOK;
2952                                         ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2953                                         ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2954                                         return NULL;
2955                                         }
2956                                 p->dialing = 1;
2957                                 return &p->subs[index].f;
2958                         }
2959                         switch(p->sig) {
2960                         case SIG_FXOLS:
2961                         case SIG_FXOGS:
2962                         case SIG_FXOKS:
2963                                 switch(ast->_state) {
2964                                 case AST_STATE_RINGING:
2965                                         zt_enable_ec(p);
2966                                         zt_train_ec(p);
2967                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2968                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2969                                         /* Make sure it stops ringing */
2970                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
2971                                         ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
2972                                         if (p->cidspill) {
2973                                                 /* Cancel any running CallerID spill */
2974                                                 free(p->cidspill);
2975                                                 p->cidspill = NULL;
2976                                         }
2977                                         p->dialing = 0;
2978                                         p->callwaitcas = 0;
2979                                         if (p->confirmanswer) {
2980                                                 /* Ignore answer if "confirm answer" is selected */
2981                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
2982                                                 p->subs[index].f.subclass = 0;
2983                                         } else if (strlen(p->dop.dialstr)) {
2984                                                 /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
2985                                                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2986                                                 if (res < 0) {
2987                                                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
2988                                                   p->dop.dialstr[0] = '\0';
2989                                                   return NULL;
2990                                                 } else {
2991                                                   ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
2992                                                   p->subs[index].f.frametype = AST_FRAME_NULL;
2993                                                   p->subs[index].f.subclass = 0;
2994                                                   p->dialing = 1;
2995                                                 }
2996                                                 p->dop.dialstr[0] = '\0';
2997                                            ast_setstate(ast, AST_STATE_DIALING);
2998                                         } else
2999                                            ast_setstate(ast, AST_STATE_UP);
3000                                         return &p->subs[index].f;
3001                                 case AST_STATE_DOWN:
3002                                         ast_setstate(ast, AST_STATE_RING);
3003                                         ast->rings = 1;
3004                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3005                                         p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
3006                                         ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
3007                                         return &p->subs[index].f;
3008                                 case AST_STATE_UP:
3009                                         /* Make sure it stops ringing */
3010                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3011                                         /* Okay -- probably call waiting*/
3012                                         if (p->owner->bridge)
3013                                                         ast_moh_stop(p->owner->bridge);
3014                                         break;
3015                                 default:
3016                                         ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
3017                                 }
3018                                 break;
3019                         case SIG_FXSLS:
3020                         case SIG_FXSGS:
3021                         case SIG_FXSKS:
3022                                 if (ast->_state == AST_STATE_RING) {
3023                                         p->ringt = RINGT;
3024                                 }
3025                                 /* Fall through */
3026                         case SIG_EM:
3027                         case SIG_EMWINK:
3028                         case SIG_FEATD:
3029                         case SIG_FEATDMF:
3030                         case SIG_E911:
3031                         case SIG_FEATB:
3032                         case SIG_SF:
3033                         case SIG_SFWINK:
3034                         case SIG_SF_FEATD:
3035                         case SIG_SF_FEATDMF:
3036                         case SIG_SF_FEATB:
3037                                 if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
3038                                         if (option_debug)
3039                                                 ast_log(LOG_DEBUG, "Ring detected\n");
3040                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3041                                         p->subs[index].f.subclass = AST_CONTROL_RING;
3042                                 } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
3043                                         if (option_debug)
3044                                                 ast_log(LOG_DEBUG, "Line answered\n");
3045                                         if (p->confirmanswer) {
3046                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
3047                                                 p->subs[index].f.subclass = 0;
3048                                         } else {
3049                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3050                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3051                                                 ast_setstate(ast, AST_STATE_UP);
3052                                         }
3053                                 } else if (ast->_state != AST_STATE_RING)
3054                                         ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
3055                                 break;
3056                         default:
3057                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
3058                         }
3059                         break;
3060                 case ZT_EVENT_RINGEROFF:
3061                         if (p->inalarm) break;
3062                         if (p->radio) break;
3063                         ast->rings++;
3064                         if ((ast->rings > p->cidrings) && (p->cidspill)) {
3065                                 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
3066                                 free(p->cidspill);
3067                                 p->cidspill = NULL;
3068                                 p->callwaitcas = 0;
3069                         }
3070                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3071                         p->subs[index].f.subclass = AST_CONTROL_RINGING;
3072                         break;
3073                 case ZT_EVENT_RINGERON:
3074                         break;
3075                 case ZT_EVENT_NOALARM:
3076                         p->inalarm = 0;
3077                         ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
3078                         manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
3079                                                                 "Channel: %d\r\n", p->channel);
3080                         break;
3081                 case ZT_EVENT_WINKFLASH:
3082                         if (p->inalarm) break;
3083                         if (p->radio) break;
3084                         /* Remember last time we got a flash-hook */
3085                         gettimeofday(&p->flashtime, NULL);
3086                         switch(p->sig) {
3087                         case SIG_FXOLS:
3088                         case SIG_FXOGS:
3089                         case SIG_FXOKS:
3090                                 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
3091                                         index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
3092                                 p->callwaitcas = 0;
3093                                 if (index == SUB_REAL) {
3094                                         if (p->subs[SUB_CALLWAIT].owner) {
3095                                                 /* Swap to call-wait */
3096                                                 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
3097                                                 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
3098                                                 p->owner = p->subs[SUB_REAL].owner;
3099                                                 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
3100                                                 if (p->owner->_state == AST_STATE_RINGING) {
3101                                                         ast_setstate(p->owner, AST_STATE_UP);
3102                                                         p->subs[SUB_REAL].needanswer = 1;
3103                                                 }
3104                                                 p->callwaitingrepeat = 0;
3105                                                 p->cidcwexpire = 0;
3106                                                 /* Start music on hold if appropriate */
3107                                                 if (!p->subs[SUB_CALLWAIT].inthreeway && p->subs[SUB_CALLWAIT].owner->bridge)
3108                                                                 ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
3109                                                 if (p->subs[SUB_REAL].owner->bridge)
3110                                                                 ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
3111                                         } else if (!p->subs[SUB_THREEWAY].owner) {
3112                                                 char callerid[256];
3113                                                 if (p->threewaycalling && !check_for_conference(p)) {
3114                                                         if (p->zaptrcallerid && p->owner)
3115                                                                 strncpy(callerid, p->owner->callerid, sizeof(callerid) - 1);
3116                                                         /* XXX This section needs much more error checking!!! XXX */
3117                                                         /* Start a 3-way call if feasible */
3118                                                         if ((ast->pbx) ||
3119                                                                         (ast->_state == AST_STATE_UP) ||
3120                                                                         (ast->_state == AST_STATE_RING)) {
3121                                                                 if (!alloc_sub(p, SUB_THREEWAY)) {
3122                                                                         /* Make new channel */
3123                                                                         chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
3124                                                                         if (p->zaptrcallerid) {
3125                                                                                 if (!p->origcallerid) {
3126                                                                                         p->origcallerid = malloc(strlen(p->callerid) + 1);
3127                                                                                         strncpy(p->origcallerid, p->callerid, strlen(p->callerid) + 1);
3128                                                                                 }
3129                                                                                 strncpy(p->callerid, callerid, sizeof(p->callerid) -1);
3130                                                                         }
3131                                                                         /* Swap things around between the three-way and real call */
3132                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3133                                                                         /* Disable echo canceller for better dialing */
3134                                                                         zt_disable_ec(p);
3135                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
3136                                                                         if (res)
3137                                                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
3138                                                                         p->owner = chan;
3139                                                                         if (chan && pthread_create(&threadid, &attr, ss_thread, chan)) {
3140                                                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
3141                                                                                 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
3142                                                                                 zt_enable_ec(p);
3143                                                                                 ast_hangup(chan);
3144                                                                         } else if (!chan) {
3145                                                                                 ast_log(LOG_WARNING, "Cannot allocate new structure on channel %d\n", p->channel);
3146                                                                         } else {
3147                                                                                 if (option_verbose > 2) 
3148                                                                                         ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d\n", p->channel);
3149                                                                                 /* Start music on hold if appropriate */
3150                                                                                 if (p->subs[SUB_THREEWAY].owner->bridge)
3151                                                                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
3152                                                                         }               
3153                                                                 } else
3154                                                                         ast_log(LOG_WARNING, "Unable to allocate three-way subchannel\n");
3155                                                         } else 
3156                                                                 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
3157                                                 }
3158                                         } else {
3159                                                 /* Already have a 3 way call */
3160                                                 if (p->subs[SUB_THREEWAY].inthreeway) {
3161                                                         /* Call is already up, drop the last person */
3162                                                         if (option_debug)
3163                                                                 ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call on %d\n", p->channel);
3164                                                         /* If the primary call isn't answered yet, use it */
3165                                                         if ((p->subs[SUB_REAL].owner->_state != AST_STATE_UP) && (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_UP)) {
3166                                                                 /* Swap back -- we're droppign the real 3-way that isn't finished yet*/
3167                                                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3168                                                                 p->owner = p->subs[SUB_REAL].owner;
3169                                                         }
3170                                                         /* Drop the last call and stop the conference */
3171                                                         if (option_verbose > 2)
3172                                                                 ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->subs[SUB_THREEWAY].owner->name);
3173                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3174                                                         p->subs[SUB_REAL].inthreeway = 0;
3175                                                         p->subs[SUB_THREEWAY].inthreeway = 0;
3176                                                 } else {
3177                                                         /* Lets see what we're up to */
3178                                                         if ((ast->pbx) ||
3179                                                                         (ast->_state == AST_STATE_UP)) {
3180                                                                 int otherindex = SUB_THREEWAY;
3181                                                                 if (option_verbose > 2)
3182                                                                         ast_verbose(VERBOSE_PREFIX_3 "Building conference on call on %s and %s\n", p->subs[SUB_THREEWAY].owner->name, p->subs[SUB_REAL].owner->name);
3183                                                                 /* Put them in the threeway, and flip */
3184                                                                 p->subs[SUB_THREEWAY].inthreeway = 1;
3185                                                                 p->subs[SUB_REAL].inthreeway = 1;
3186                                                                 if (ast->_state == AST_STATE_UP) {
3187                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3188                                                                         otherindex = SUB_REAL;
3189