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