b5b966535b08706ca3cd65aba96c92a5ee912c96
[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                 p->proceeding = 1;
1669                 ast_setstate(ast, AST_STATE_DIALING);
1670                 pri_rel(p->pri);
1671                 break;
1672 #endif          
1673         case 0:
1674                 /* Special pseudo -- automatically up*/
1675                 ast_setstate(ast, AST_STATE_UP);
1676                 break;          
1677         default:
1678                 ast_log(LOG_DEBUG, "not yet implemented\n");
1679                 ast_mutex_unlock(&p->lock);
1680                 return -1;
1681         }
1682         ast_mutex_unlock(&p->lock);
1683         return 0;
1684 }
1685
1686 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1687 {
1688         int owned = 0;
1689         int i = 0;
1690
1691         if (!now) {
1692                 if (cur->owner) {
1693                         owned = 1;
1694                 }
1695
1696                 for (i = 0; i < 3; i++) {
1697                         if (cur->subs[i].owner) {
1698                                 owned = 1;
1699                         }
1700                 }
1701                 if (!owned) {
1702                         if (prev) {
1703                                 prev->next = cur->next;
1704                                 if (prev->next)
1705                                         prev->next->prev = prev;
1706                                 else
1707                                         ifend = prev;
1708                         } else {
1709                                 iflist = cur->next;
1710                                 if (iflist)
1711                                         iflist->prev = NULL;
1712                                 else
1713                                         ifend = NULL;
1714                         }
1715                         if (cur->subs[SUB_REAL].zfd > -1) {
1716                                 zt_close(cur->subs[SUB_REAL].zfd);
1717                         }
1718                         free(cur);
1719                 }
1720         } else {
1721                 if (prev) {
1722                         prev->next = cur->next;
1723                         if (prev->next)
1724                                 prev->next->prev = prev;
1725                         else
1726                                 ifend = prev;
1727                 } else {
1728                         iflist = cur->next;
1729                         if (iflist)
1730                                 iflist->prev = NULL;
1731                         else
1732                                 ifend = NULL;
1733                 }
1734                 if (cur->subs[SUB_REAL].zfd > -1) {
1735                         zt_close(cur->subs[SUB_REAL].zfd);
1736                 }
1737                 free(cur);
1738         }
1739         return 0;
1740 }
1741
1742
1743 static int zt_hangup(struct ast_channel *ast)
1744 {
1745         int res;
1746         int index,x, law;
1747         static int restore_gains(struct zt_pvt *p);
1748         struct zt_pvt *p = ast->pvt->pvt;
1749         struct zt_pvt *tmp = NULL;
1750         struct zt_pvt *prev = NULL;
1751         ZT_PARAMS par;
1752
1753         if (option_debug)
1754                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1755         if (!ast->pvt->pvt) {
1756                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1757                 return 0;
1758         }
1759         
1760         ast_mutex_lock(&p->lock);
1761         
1762         index = zt_get_index(ast, p, 1);
1763
1764         if (p->sig == SIG_PRI) {
1765                 x = 1;
1766                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
1767         }
1768
1769         x = 0;
1770         zt_confmute(p, 0);
1771         restore_gains(p);
1772         if (p->origcallerid) {
1773                 strncpy(p->callerid, p->origcallerid, sizeof(p->callerid) - 1);
1774                 free(p->origcallerid);
1775                 p->origcallerid = NULL;
1776         }       
1777         if (p->dsp)
1778                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
1779         if (p->exten)
1780                 strcpy(p->exten, "");
1781
1782         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1783                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
1784         p->ignoredtmf = 0;
1785         
1786         if (index > -1) {
1787                 /* Real channel, do some fixup */
1788                 p->subs[index].owner = NULL;
1789                 p->subs[index].needanswer = 0;
1790                 p->subs[index].needringing = 0;
1791                 p->subs[index].needbusy = 0;
1792                 p->subs[index].needcongestion = 0;
1793                 p->subs[index].linear = 0;
1794                 p->subs[index].needcallerid = 0;
1795                 zt_setlinear(p->subs[index].zfd, 0);
1796                 if (index == SUB_REAL) {
1797                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
1798                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
1799                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
1800                                         /* We had flipped over to answer a callwait and now it's gone */
1801                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
1802                                         /* Move to the call-wait, but un-own us until they flip back. */
1803                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1804                                         unalloc_sub(p, SUB_CALLWAIT);
1805                                         p->owner = NULL;
1806                                 } else {
1807                                         /* The three way hung up, but we still have a call wait */
1808                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
1809                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
1810                                         unalloc_sub(p, SUB_THREEWAY);
1811                                         if (p->subs[SUB_REAL].inthreeway) {
1812                                                 /* This was part of a three way call.  Immediately make way for
1813                                                    another call */
1814                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1815                                                 p->owner = p->subs[SUB_REAL].owner;
1816                                         } else {
1817                                                 /* This call hasn't been completed yet...  Set owner to NULL */
1818                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1819                                                 p->owner = NULL;
1820                                         }
1821                                         p->subs[SUB_REAL].inthreeway = 0;
1822                                 }
1823                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
1824                                 /* Move to the call-wait and switch back to them. */
1825                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
1826                                 unalloc_sub(p, SUB_CALLWAIT);
1827                                 p->owner = p->subs[SUB_REAL].owner;
1828                                 if (p->owner->_state != AST_STATE_UP)
1829                                         p->subs[SUB_REAL].needanswer = 1;
1830                                 if (p->subs[SUB_REAL].owner->bridge)
1831                                         ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
1832                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
1833                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
1834                                 unalloc_sub(p, SUB_THREEWAY);
1835                                 if (p->subs[SUB_REAL].inthreeway) {
1836                                         /* This was part of a three way call.  Immediately make way for
1837                                            another call */
1838                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
1839                                         p->owner = p->subs[SUB_REAL].owner;
1840                                 } else {
1841                                         /* This call hasn't been completed yet...  Set owner to NULL */
1842                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
1843                                         p->owner = NULL;
1844                                 }
1845                                 p->subs[SUB_REAL].inthreeway = 0;
1846                         }
1847                 } else if (index == SUB_CALLWAIT) {
1848                         /* Ditch the holding callwait call, and immediately make it availabe */
1849                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1850                                 /* This is actually part of a three way, placed on hold.  Place the third part
1851                                    on music on hold now */
1852                                 if (p->subs[SUB_THREEWAY].owner && p->subs[SUB_THREEWAY].owner->bridge)
1853                                         ast_moh_start(p->subs[SUB_THREEWAY].owner->bridge, NULL);
1854                                 p->subs[SUB_THREEWAY].inthreeway = 0;
1855                                 /* Make it the call wait now */
1856                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
1857                                 unalloc_sub(p, SUB_THREEWAY);
1858                         } else
1859                                 unalloc_sub(p, SUB_CALLWAIT);
1860                 } else if (index == SUB_THREEWAY) {
1861                         if (p->subs[SUB_CALLWAIT].inthreeway) {
1862                                 /* The other party of the three way call is currently in a call-wait state.
1863                                    Start music on hold for them, and take the main guy out of the third call */
1864                                 if (p->subs[SUB_CALLWAIT].owner && p->subs[SUB_CALLWAIT].owner->bridge)
1865                                         ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
1866                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
1867                         }
1868                         p->subs[SUB_REAL].inthreeway = 0;
1869                         /* If this was part of a three way call index, let us make
1870                            another three way call */
1871                         unalloc_sub(p, SUB_THREEWAY);
1872                 } else {
1873                         /* This wasn't any sort of call, but how are we an index? */
1874                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1875                 }
1876         }
1877
1878
1879         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
1880                 p->owner = NULL;
1881                 p->ringt = 0;
1882                 p->distinctivering = 0;
1883                 p->confirmanswer = 0;
1884                 p->cidrings = 1;
1885                 p->outgoing = 0;
1886                 p->digital = 0;
1887                 p->faxhandled = 0;
1888                 p->pulsedial = 0;
1889                 p->onhooktime = time(NULL);
1890 #ifdef PRI_EVENT_PROCEEDING
1891                 p->proceeding = 0;
1892 #endif
1893 #ifdef PRI_EVENT_SETUP_ACK
1894                 p->setup_ack = 0;
1895 #endif
1896                 if (p->dsp) {
1897                         ast_dsp_free(p->dsp);
1898                         p->dsp = NULL;
1899                 }
1900
1901                 law = ZT_LAW_DEFAULT;
1902                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
1903                 if (res < 0) 
1904                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
1905                 /* Perform low level hangup if no owner left */
1906 #ifdef ZAPATA_PRI
1907                 if (p->sig == SIG_PRI) {
1908                         if (p->call) {
1909                                 if (!pri_grab(p, p->pri)) {
1910 #ifndef NEW_PRI_HANGUP
1911                                         if (!p->alreadyhungup) {
1912                                                 res = pri_disconnect(p->pri->pri, p->call, PRI_CAUSE_NORMAL_CLEARING);
1913                                         } else {
1914                                                 pri_release(p->pri->pri, p->call, -1);
1915                                                 p->call = NULL;
1916                                                 p->alreadyhungup = 0;
1917                                         }
1918 #else
1919 #ifndef PRI_HANGUP
1920 #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
1921 #endif
1922                                         if (p->alreadyhungup) {
1923                                                 pri_hangup(p->pri->pri, p->call, -1);
1924                                                 p->call = NULL;
1925                                         } else {
1926                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
1927                                                 int icause = ast->hangupcause ? hangup_cause2pri(ast->hangupcause) : -1;
1928                                                 p->alreadyhungup = 1;
1929                                                 if (cause) {
1930                                                         if (atoi(cause))
1931                                                                 icause = atoi(cause);
1932                                                 }
1933                                                 pri_hangup(p->pri->pri, p->call, icause);
1934                                         }
1935 #endif
1936                                         if (res < 0) 
1937                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
1938                                         pri_rel(p->pri);                        
1939                                 } else {
1940                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1941                                         res = -1;
1942                                 }
1943                         } else
1944                                 res = 0;
1945
1946                 } else 
1947 #endif
1948 #ifdef ZAPATA_R2
1949                 if (p->sig == SIG_R2) {
1950                         if (p->hasr2call) {
1951                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
1952                                 p->hasr2call = 0;
1953                                 res = 0;
1954                         } else
1955                                 res = 0;
1956
1957                 } else 
1958 #endif
1959                 if (p->sig)
1960                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
1961                 if (res < 0) {
1962                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1963                 }
1964                 switch(p->sig) {
1965                 case SIG_FXOGS:
1966                 case SIG_FXOLS:
1967                 case SIG_FXOKS:
1968                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
1969                         if (!res) {
1970 #if 0
1971                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
1972 #endif
1973                                 /* If they're off hook, try playing congestion */
1974                                 if (par.rxisoffhook)
1975                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
1976                                 else
1977                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1978                         }
1979                         break;
1980                 case SIG_FXSGS:
1981                 case SIG_FXSLS:
1982                 case SIG_FXSKS:
1983                         /* Make sure we're not made available for at least two seconds */
1984                         time(&p->guardtime);
1985                         p->guardtime += 2;
1986                         break;
1987                 default:
1988                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
1989                 }
1990                 if (p->cidspill)
1991                         free(p->cidspill);
1992                 if (p->sig)
1993                         zt_disable_ec(p);
1994                 x = 0;
1995                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1996                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1997                 p->didtdd = 0;
1998                 p->cidspill = NULL;
1999                 p->callwaitcas = 0;
2000                 p->callwaiting = p->permcallwaiting;
2001                 p->hidecallerid = p->permhidecallerid;
2002                 p->dialing = 0;
2003                 strcpy(p->rdnis, "");
2004                 update_conf(p);
2005                 /* Restore data mode */
2006                 if (p->sig == SIG_PRI) {
2007                         x = 0;
2008                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2009                 }
2010
2011                 restart_monitor();
2012         }
2013
2014
2015         p->callwaitingrepeat = 0;
2016         p->cidcwexpire = 0;
2017         ast->pvt->pvt = NULL;
2018         ast_mutex_unlock(&p->lock);
2019         ast_mutex_lock(&usecnt_lock);
2020         usecnt--;
2021         if (usecnt < 0) 
2022                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2023         ast_mutex_unlock(&usecnt_lock);
2024         ast_update_use_count();
2025         if (option_verbose > 2) 
2026                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2027
2028         ast_mutex_lock(&iflock);
2029         tmp = iflist;
2030         prev = NULL;
2031         if (p->destroy) {
2032                 while (tmp) {
2033                         if (tmp == p) {
2034                                 destroy_channel(prev, tmp, 0);
2035                                 break;
2036                         } else {
2037                                 prev = tmp;
2038                                 tmp = tmp->next;
2039                         }
2040                 }
2041         }
2042         ast_mutex_unlock(&iflock);
2043         return 0;
2044 }
2045
2046 static int zt_answer(struct ast_channel *ast)
2047 {
2048         struct zt_pvt *p = ast->pvt->pvt;
2049         int res=0;
2050         int index;
2051         int oldstate = ast->_state;
2052         ast_setstate(ast, AST_STATE_UP);
2053         ast_mutex_lock(&p->lock);
2054         index = zt_get_index(ast, p, 0);
2055         if (index < 0)
2056                 index = SUB_REAL;
2057         /* nothing to do if a radio channel */
2058         if (p->radio) {
2059                 ast_mutex_unlock(&p->lock);
2060                 return 0;
2061         }
2062         switch(p->sig) {
2063         case SIG_FXSLS:
2064         case SIG_FXSGS:
2065         case SIG_FXSKS:
2066                 p->ringt = 0;
2067                 /* Fall through */
2068         case SIG_EM:
2069         case SIG_EM_E1:
2070         case SIG_EMWINK:
2071         case SIG_FEATD:
2072         case SIG_FEATDMF:
2073         case SIG_E911:
2074         case SIG_FEATB:
2075         case SIG_SF:
2076         case SIG_SFWINK:
2077         case SIG_SF_FEATD:
2078         case SIG_SF_FEATDMF:
2079         case SIG_SF_FEATB:
2080         case SIG_FXOLS:
2081         case SIG_FXOGS:
2082         case SIG_FXOKS:
2083                 /* Pick up the line */
2084                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2085                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2086                 tone_zone_play_tone(p->subs[index].zfd, -1);
2087                 p->dialing = 0;
2088                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2089                         if (oldstate == AST_STATE_RINGING) {
2090                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2091                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2092                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2093                                 p->owner = p->subs[SUB_REAL].owner;
2094                         }
2095                 }
2096                 if (p->sig & __ZT_SIG_FXS) {
2097                         zt_enable_ec(p);
2098                         zt_train_ec(p);
2099                 }
2100                 break;
2101 #ifdef ZAPATA_PRI
2102         case SIG_PRI:
2103                 /* Send a pri acknowledge */
2104                 if (!pri_grab(p, p->pri)) {
2105                         p->proceeding = 1;
2106                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2107                         pri_rel(p->pri);
2108                 } else {
2109                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2110                         res= -1;
2111                 }
2112                 break;
2113 #endif
2114 #ifdef ZAPATA_R2
2115         case SIG_R2:
2116                 res = mfcr2_AnswerCall(p->r2, NULL);
2117                 if (res)
2118                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2119                 break;
2120 #endif                  
2121         case 0:
2122                 ast_mutex_unlock(&p->lock);
2123                 return 0;
2124         default:
2125                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2126                 res = -1;
2127         }
2128         ast_mutex_unlock(&p->lock);
2129         return res;
2130 }
2131
2132 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2133 {
2134 char    *cp;
2135 int     x;
2136
2137         struct zt_pvt *p = chan->pvt->pvt;
2138
2139         
2140         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2141                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2142            {
2143                 errno = ENOSYS;
2144                 return -1;
2145            }
2146         cp = (char *)data;
2147         if ((!cp) || (datalen < 1))
2148            {
2149                 errno = EINVAL;
2150                 return -1;
2151            }
2152         switch(option) {
2153             case AST_OPTION_TONE_VERIFY:
2154                 if (!p->dsp)
2155                         break;
2156                 switch(*cp) {
2157                     case 1:
2158                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2159                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2160                         break;
2161                     case 2:
2162                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2163                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2164                         break;
2165                     default:
2166                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2167                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2168                         break;
2169                 }
2170                 break;
2171             case AST_OPTION_TDD:  /* turn on or off TDD */
2172                 if (!*cp) { /* turn it off */
2173                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2174                         if (p->tdd) tdd_free(p->tdd);
2175                         p->tdd = 0;
2176                         p->mate = 0;
2177                         break;
2178                 }
2179                 if (*cp == 2)
2180                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2181                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2182                 p->mate = 0;
2183                 zt_disable_ec(p);
2184                 /* otherwise, turn it on */
2185                 if (!p->didtdd) { /* if havent done it yet */
2186                         unsigned char mybuf[41000],*buf;
2187                         int size,res,fd,len;
2188                         int index;
2189                         struct pollfd fds[1];
2190                         buf = mybuf;
2191                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2192                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2193                         len = 40000;
2194                         index = zt_get_index(chan, p, 0);
2195                         if (index < 0) {
2196                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2197                                 return -1;
2198                         }
2199                         fd = p->subs[index].zfd;
2200                         while(len) {
2201                                 if (ast_check_hangup(chan)) return -1;
2202                                 size = len;
2203                                 if (size > READ_SIZE)
2204                                         size = READ_SIZE;
2205                                 fds[0].fd = fd;
2206                                 fds[0].events = POLLPRI | POLLOUT;
2207                                 res = poll(fds, 1, -1);
2208                                 if (!res) {
2209                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2210                                         continue;
2211                                 }
2212                                   /* if got exception */
2213                                 if (fds[0].revents & POLLPRI) return -1;
2214                                 if (!(fds[0].revents & POLLOUT)) {
2215                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2216                                         continue;
2217                                 }
2218                                 res = write(fd, buf, size);
2219                                 if (res != size) {
2220                                         if (res == -1) return -1;
2221                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2222                                         break;
2223                                 }
2224                                 len -= size;
2225                                 buf += size;
2226                         }
2227                         p->didtdd = 1; /* set to have done it now */            
2228                 }
2229                 if (*cp == 2) { /* Mate mode */
2230                         if (p->tdd) tdd_free(p->tdd);
2231                         p->tdd = 0;
2232                         p->mate = 1;
2233                         break;
2234                         }               
2235                 if (!p->tdd) { /* if we dont have one yet */
2236                         p->tdd = tdd_new(); /* allocate one */
2237                 }               
2238                 break;
2239             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2240                 if (!*cp)
2241                 {               
2242                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2243                         x = 0;
2244                 }
2245                 else
2246                 {               
2247                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2248                         x = 1;
2249                 }
2250                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2251                 break;
2252             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2253                 if (!*cp)
2254                 {               
2255                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2256                         x = 0;
2257                         zt_disable_ec(p);
2258                 }
2259                 else
2260                 {               
2261                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2262                         x = 1;
2263                 }
2264                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2265                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2266                 break;
2267         }
2268         errno = 0;
2269         return 0;
2270 }
2271
2272 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2273 {
2274         /* Unlink a specific slave or all slaves/masters from a given master */
2275         int x;
2276         int hasslaves;
2277         if (!master)
2278                 return;
2279         if (needlock) {
2280                 ast_mutex_lock(&master->lock);
2281                 if (slave) {
2282                         while(ast_mutex_trylock(&slave->lock)) {
2283                                 ast_mutex_unlock(&master->lock);
2284                                 usleep(1);
2285                                 ast_mutex_lock(&master->lock);
2286                         }
2287                 }
2288         }
2289         hasslaves = 0;
2290         for (x=0;x<MAX_SLAVES;x++) {
2291                 if (master->slaves[x]) {
2292                         if (!slave || (master->slaves[x] == slave)) {
2293                                 /* Take slave out of the conference */
2294                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2295                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2296                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2297                                 master->slaves[x]->master = NULL;
2298                                 master->slaves[x] = NULL;
2299                         } else
2300                                 hasslaves = 1;
2301                 }
2302                 if (!hasslaves)
2303                         master->inconference = 0;
2304         }
2305         if (!slave) {
2306                 if (master->master) {
2307                         /* Take master out of the conference */
2308                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2309                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2310                         hasslaves = 0;
2311                         for (x=0;x<MAX_SLAVES;x++) {
2312                                 if (master->master->slaves[x] == master)
2313                                         master->master->slaves[x] = NULL;
2314                                 else if (master->master->slaves[x])
2315                                         hasslaves = 1;
2316                         }
2317                         if (!hasslaves)
2318                                 master->master->inconference = 0;
2319                 }
2320                 master->master = NULL;
2321         }
2322         update_conf(master);
2323         if (needlock) {
2324                 if (slave)
2325                         ast_mutex_unlock(&slave->lock);
2326                 ast_mutex_unlock(&master->lock);
2327         }
2328 }
2329
2330 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2331         int x;
2332         if (!slave || !master) {
2333                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2334                 return;
2335         }
2336         for (x=0;x<MAX_SLAVES;x++) {
2337                 if (!master->slaves[x]) {
2338                         master->slaves[x] = slave;
2339                         break;
2340                 }
2341         }
2342         if (x >= MAX_SLAVES) {
2343                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2344                 master->slaves[MAX_SLAVES - 1] = slave;
2345         }
2346         if (slave->master) 
2347                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2348         slave->master = master;
2349         
2350         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2351 }
2352
2353 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2354 {
2355         struct ast_channel *who = NULL, *cs[3];
2356         struct zt_pvt *p0, *p1, *op0, *op1;
2357         struct zt_pvt *master=NULL, *slave=NULL;
2358         struct ast_frame *f;
2359         int to;
2360         int inconf = 0;
2361         int nothingok = 0;
2362         int ofd1, ofd2;
2363         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2364         int os1 = -1, os2 = -1;
2365         struct ast_channel *oc1, *oc2;
2366
2367         /* if need DTMF, cant native bridge */
2368         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2369                 return -2;
2370                 
2371         ast_mutex_lock(&c0->lock);
2372         ast_mutex_lock(&c1->lock);
2373
2374         p0 = c0->pvt->pvt;
2375         p1 = c1->pvt->pvt;
2376         /* cant do pseudo-channels here */
2377         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2378                 ast_mutex_unlock(&c0->lock);
2379                 ast_mutex_unlock(&c1->lock);
2380                 return -2;
2381         }
2382
2383         op0 = p0 = c0->pvt->pvt;
2384         op1 = p1 = c1->pvt->pvt;
2385         ofd1 = c0->fds[0];
2386         ofd2 = c1->fds[0];
2387         oi1 = zt_get_index(c0, p0, 0);
2388         oi2 = zt_get_index(c1, p1, 0);
2389         oc1 = p0->owner;
2390         oc2 = p1->owner;
2391         if ((oi1 < 0) || (oi2 < 0)) {
2392                 ast_mutex_unlock(&c0->lock);
2393                 ast_mutex_unlock(&c1->lock);
2394                 return -1;
2395         }
2396
2397
2398
2399         ast_mutex_lock(&p0->lock);
2400         if (ast_mutex_trylock(&p1->lock)) {
2401                 /* Don't block, due to potential for deadlock */
2402                 ast_mutex_unlock(&p0->lock);
2403                 ast_mutex_unlock(&c0->lock);
2404                 ast_mutex_unlock(&c1->lock);
2405                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2406                 return -3;
2407         }
2408         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2409                 if (!p0->owner || !p1->owner) {
2410                         /* Currently unowned -- Do nothing.  */
2411                         nothingok = 1;
2412                 } else {
2413                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2414                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2415                                 master = p0;
2416                                 slave = p1;
2417                                 inconf = 1;
2418                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2419                                 master = p1;
2420                                 slave = p0;
2421                                 inconf = 1;
2422                         } else {
2423                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2424                                 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,
2425                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2426                         }
2427                 }
2428         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2429                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2430                         master = p1;
2431                         slave = p0;
2432                 } else {
2433                         nothingok = 1;
2434                 }
2435         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2436                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2437                         master = p0;
2438                         slave = p1;
2439                 } else {
2440                         nothingok  = 1;
2441                 }
2442         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2443                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2444                    don't put us in anything */
2445                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2446                         master = p1;
2447                         slave = p0;
2448                 } else {
2449                         nothingok = 1;
2450                 }
2451         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2452                 /* Same as previous */
2453                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2454                         master = p0;
2455                         slave = p1;
2456                 } else {
2457                         nothingok = 1;
2458                 }
2459         }
2460         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2461                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2462         if (master && slave) {
2463                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2464                    in an active threeway call with a channel that is ringing, we should
2465                    indicate ringing. */
2466                 if ((oi2 == SUB_THREEWAY) && 
2467                         p1->subs[SUB_THREEWAY].inthreeway && 
2468                         p1->subs[SUB_REAL].owner && 
2469                         p1->subs[SUB_REAL].inthreeway && 
2470                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2471                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2472                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2473                                 os2 = p1->subs[SUB_REAL].owner->_state;
2474                 } else {
2475                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2476                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2477                 }
2478                 if ((oi1 == SUB_THREEWAY) && 
2479                         p0->subs[SUB_THREEWAY].inthreeway && 
2480                         p0->subs[SUB_REAL].owner && 
2481                         p0->subs[SUB_REAL].inthreeway && 
2482                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2483                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2484                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2485                                 os1 = p0->subs[SUB_REAL].owner->_state;
2486                 } else {
2487                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2488                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2489                 }
2490                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2491                         if (!p0->echocanbridged || !p1->echocanbridged) {
2492                                 /* Disable echo cancellation if appropriate */
2493                                 zt_disable_ec(p0);
2494                                 zt_disable_ec(p1);
2495                         }
2496                 }
2497                 zt_link(slave, master);
2498                 master->inconference = inconf;
2499         } else if (!nothingok)
2500                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2501
2502         update_conf(p0);
2503         update_conf(p1);
2504         t1 = p0->subs[SUB_REAL].inthreeway;
2505         t2 = p1->subs[SUB_REAL].inthreeway;
2506
2507         ast_mutex_unlock(&p0->lock);
2508         ast_mutex_unlock(&p1->lock);
2509
2510         ast_mutex_unlock(&c0->lock);
2511         ast_mutex_unlock(&c1->lock);
2512
2513         /* Native bridge failed */
2514         if ((!master || !slave) && !nothingok) {
2515                 if (op0 == p0)
2516                         zt_enable_ec(p0);
2517                 if (op1 == p1)
2518                         zt_enable_ec(p1);
2519                 return -1;
2520         }
2521         
2522         cs[0] = c0;
2523         cs[1] = c1;
2524         cs[2] = NULL;
2525         for (;;) {
2526                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2527                    and then balking if anything is wrong */
2528                 ast_mutex_lock(&c0->lock);
2529                 ast_mutex_lock(&c1->lock);
2530                 p0 = c0->pvt->pvt;
2531                 p1 = c1->pvt->pvt;
2532                 if (op0 == p0)
2533                         i1 = zt_get_index(c0, p0, 1);
2534                 if (op1 == p1)
2535                         i2 = zt_get_index(c1, p1, 1);
2536                 ast_mutex_unlock(&c0->lock);
2537                 ast_mutex_unlock(&c1->lock);
2538                 if ((op0 != p0) || (op1 != p1) || 
2539                     (ofd1 != c0->fds[0]) || 
2540                         (ofd2 != c1->fds[0]) ||
2541                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2542                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2543                     (oc1 != p0->owner) || 
2544                         (oc2 != p1->owner) ||
2545                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2546                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2547                         (oi1 != i1) ||
2548                         (oi2 != i2)) {
2549                         if (slave && master)
2550                                 zt_unlink(slave, master, 1);
2551                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2552                                                                         op0->channel, oi1, op1->channel, oi2);
2553                         if (op0 == p0)
2554                                 zt_enable_ec(p0);
2555                         if (op1 == p1)
2556                                 zt_enable_ec(p1);
2557                         return -3;
2558                 }
2559                 to = -1;
2560                 who = ast_waitfor_n(cs, 2, &to);
2561                 if (!who) {
2562                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2563                         continue;
2564                 }
2565                 if (who->pvt->pvt == op0) 
2566                         op0->ignoredtmf = 1;
2567                 else if (who->pvt->pvt == op1)
2568                         op1->ignoredtmf = 1;
2569                 f = ast_read(who);
2570                 if (who->pvt->pvt == op0) 
2571                         op0->ignoredtmf = 0;
2572                 else if (who->pvt->pvt == op1)
2573                         op1->ignoredtmf = 0;
2574                 if (!f) {
2575                         *fo = NULL;
2576                         *rc = who;
2577                         if (slave && master)
2578                                 zt_unlink(slave, master, 1);
2579                         if (op0 == p0)
2580                                 zt_enable_ec(p0);
2581                         if (op1 == p1)
2582                                 zt_enable_ec(p1);
2583                         return 0;
2584                 }
2585                 if (f->frametype == AST_FRAME_DTMF) {
2586                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2587                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2588                                 *fo = f;
2589                                 *rc = who;
2590                                 if (slave && master)
2591                                         zt_unlink(slave, master, 1);
2592                                 return 0;
2593                         } else if ((who == c0) && p0->pulsedial) {
2594                                 ast_write(c1, f);
2595                         } else if ((who == c1) && p1->pulsedial) {
2596                                 ast_write(c0, f);
2597                         }
2598                 }
2599                 ast_frfree(f);
2600
2601                 /* Swap who gets priority */
2602                 cs[2] = cs[0];
2603                 cs[0] = cs[1];
2604                 cs[1] = cs[2];
2605         }
2606 }
2607
2608 static int zt_indicate(struct ast_channel *chan, int condition);
2609
2610 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2611 {
2612         struct zt_pvt *p = newchan->pvt->pvt;
2613         int x;
2614         ast_mutex_lock(&p->lock);
2615         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2616         if (p->owner == oldchan)
2617                 p->owner = newchan;
2618         for (x=0;x<3;x++)
2619                 if (p->subs[x].owner == oldchan) {
2620                         if (!x)
2621                                 zt_unlink(NULL, p, 0);
2622                         p->subs[x].owner = newchan;
2623                 }
2624         if (newchan->_state == AST_STATE_RINGING) 
2625                 zt_indicate(newchan, AST_CONTROL_RINGING);
2626         update_conf(p);
2627         ast_mutex_unlock(&p->lock);
2628         return 0;
2629 }
2630
2631 static int zt_ring_phone(struct zt_pvt *p)
2632 {
2633         int x;
2634         int res;
2635         /* Make sure our transmit state is on hook */
2636         x = 0;
2637         x = ZT_ONHOOK;
2638         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2639         do {
2640                 x = ZT_RING;
2641                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2642 #if 0
2643                 printf("Res: %d, error: %s\n", res, strerror(errno));
2644 #endif                                          
2645                 if (res) {
2646                         switch(errno) {
2647                         case EBUSY:
2648                         case EINTR:
2649                                 /* Wait just in case */
2650                                 usleep(10000);
2651                                 continue;
2652                         case EINPROGRESS:
2653                                 res = 0;
2654                                 break;
2655                         default:
2656                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2657                                 res = 0;
2658                         }
2659                 }
2660         } while (res);
2661         return res;
2662 }
2663
2664 static void *ss_thread(void *data);
2665
2666 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2667
2668 static int attempt_transfer(struct zt_pvt *p)
2669 {
2670         /* In order to transfer, we need at least one of the channels to
2671            actually be in a call bridge.  We can't conference two applications
2672            together (but then, why would we want to?) */
2673         if (p->subs[SUB_REAL].owner->bridge) {
2674                 /* The three-way person we're about to transfer to could still be in MOH, so
2675                    stop if now if appropriate */
2676                 if (p->subs[SUB_THREEWAY].owner->bridge)
2677                         ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2678                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2679                         ast_indicate(p->subs[SUB_REAL].owner->bridge, AST_CONTROL_RINGING);
2680                 }
2681                 if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, p->subs[SUB_REAL].owner->bridge)) {
2682                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2683                                         p->subs[SUB_REAL].owner->bridge->name, p->subs[SUB_THREEWAY].owner->name);
2684                         return -1;
2685                 }
2686                 /* Orphan the channel */
2687                 unalloc_sub(p, SUB_THREEWAY);
2688         } else if (p->subs[SUB_THREEWAY].owner->bridge) {
2689                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2690                         ast_indicate(p->subs[SUB_THREEWAY].owner->bridge, AST_CONTROL_RINGING);
2691                 }
2692                 ast_moh_stop(p->subs[SUB_THREEWAY].owner->bridge);
2693                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, p->subs[SUB_THREEWAY].owner->bridge)) {
2694                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2695                                         p->subs[SUB_THREEWAY].owner->bridge->name, p->subs[SUB_REAL].owner->name);
2696                         return -1;
2697                 }
2698                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2699                 unalloc_sub(p, SUB_THREEWAY);
2700                 /* Tell the caller not to hangup */
2701                 return 1;
2702         } else {
2703                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
2704                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
2705                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2706         }
2707         return 0;
2708 }
2709
2710 #ifdef ZAPATA_R2
2711 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
2712 {
2713         struct ast_frame *f;
2714         f = &p->subs[index].f;
2715         if (!p->r2) {
2716                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
2717                 return NULL;
2718         }
2719         switch(e->e) {
2720         case MFCR2_EVENT_BLOCKED:
2721                 if (option_verbose > 2)
2722                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
2723                 break;
2724         case MFCR2_EVENT_UNBLOCKED:
2725                 if (option_verbose > 2)
2726                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
2727                 break;
2728         case MFCR2_EVENT_CONFIG_ERR:
2729                 if (option_verbose > 2)
2730                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
2731                 break;
2732         case MFCR2_EVENT_RING:
2733                 if (option_verbose > 2)
2734                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
2735                 break;
2736         case MFCR2_EVENT_HANGUP:
2737                 if (option_verbose > 2)
2738                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
2739                 break;
2740         case MFCR2_EVENT_RINGING:
2741                 if (option_verbose > 2)
2742                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
2743                 break;
2744         case MFCR2_EVENT_ANSWER:
2745                 if (option_verbose > 2)
2746                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
2747                 break;
2748         case MFCR2_EVENT_HANGUP_ACK:
2749                 if (option_verbose > 2)
2750                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
2751                 break;
2752         case MFCR2_EVENT_IDLE:
2753                 if (option_verbose > 2)
2754                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
2755                 break;
2756         default:
2757                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
2758                 break;
2759         }
2760         return f;
2761 }
2762
2763 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
2764 {
2765         int x;
2766         int res;
2767         mfcr2_event_t *e;
2768         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
2769         if (res) {
2770                 ast_log(LOG_WARNING, "Unable to check received bits\n");
2771                 return NULL;
2772         }
2773         if (!p->r2) {
2774                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
2775                 return NULL;
2776         }
2777         e = mfcr2_cas_signaling_event(p->r2, x);
2778         return e;
2779 }
2780 #endif
2781
2782 static int check_for_conference(struct zt_pvt *p)
2783 {
2784         ZT_CONFINFO ci;
2785         /* Fine if we already have a master, etc */
2786         if (p->master || (p->confno > -1))
2787                 return 0;
2788         memset(&ci, 0, sizeof(ci));
2789         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
2790                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
2791                 return 0;
2792         }
2793         /* If we have no master and don't have a confno, then 
2794            if we're in a conference, it's probably a MeetMe room or
2795            some such, so don't let us 3-way out! */
2796         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
2797                 if (option_verbose > 2) 
2798                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
2799                 return 1;
2800         }
2801         return 0;
2802 }
2803
2804 static int get_alarms(struct zt_pvt *p)
2805 {
2806         int res;
2807         ZT_SPANINFO zi;
2808         memset(&zi, 0, sizeof(zi));
2809         zi.spanno = p->span;
2810         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
2811         if (res < 0) {
2812                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
2813                 return 0;
2814         }
2815         return zi.alarms;
2816 }
2817                         
2818 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
2819 {
2820         int res,x;
2821         int index;
2822         char *c;
2823         struct zt_pvt *p = ast->pvt->pvt;
2824         pthread_t threadid;
2825         pthread_attr_t attr;
2826         struct ast_channel *chan;
2827         pthread_attr_init(&attr);
2828         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2829         index = zt_get_index(ast, p, 0);
2830         p->subs[index].f.frametype = AST_FRAME_NULL;
2831         p->subs[index].f.datalen = 0;
2832         p->subs[index].f.samples = 0;
2833         p->subs[index].f.mallocd = 0;
2834         p->subs[index].f.offset = 0;
2835         p->subs[index].f.src = "zt_handle_event";
2836         p->subs[index].f.data = NULL;
2837         if (index < 0)
2838                 return &p->subs[index].f;
2839         if (p->fake_event) {
2840                 res = p->fake_event;
2841                 p->fake_event = 0;
2842         } else
2843                 res = zt_get_event(p->subs[index].zfd);
2844         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
2845         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFDIGIT)) {
2846                 if (res & ZT_EVENT_PULSEDIGIT)
2847                         p->pulsedial = 1;
2848                 else
2849                         p->pulsedial = 0;
2850                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
2851                 p->subs[index].f.frametype = AST_FRAME_DTMF;
2852                 p->subs[index].f.subclass = res & 0xff;
2853                 /* Return the captured digit */
2854                 return &p->subs[index].f;
2855         }
2856         switch(res) {
2857                 case ZT_EVENT_BITSCHANGED:
2858                         if (p->sig == SIG_R2) {
2859 #ifdef ZAPATA_R2
2860                                 struct ast_frame  *f = &p->subs[index].f;
2861                                 mfcr2_event_t *e;
2862                                 e = r2_get_event_bits(p);
2863                                 if (e)
2864                                         f = handle_r2_event(p, e, index);
2865                                 return f;
2866 #else                           
2867                                 break;
2868 #endif
2869                         }
2870                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
2871                 case ZT_EVENT_PULSE_START:
2872                         /* Stop tone if there's a pulse start and the PBX isn't started */
2873                         if (!ast->pbx)
2874                                 tone_zone_play_tone(p->subs[index].zfd, -1);
2875                         break;  
2876                 case ZT_EVENT_DIALCOMPLETE:
2877                         if (p->inalarm) break;
2878                         if (p->radio) break;
2879                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
2880                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
2881                                 return NULL;
2882                         }
2883                         if (!x) { /* if not still dialing in driver */
2884                                 zt_enable_ec(p);
2885                                 if (p->echobreak) {
2886                                         zt_train_ec(p);
2887                                         strcpy(p->dop.dialstr, p->echorest);
2888                                         p->dop.op = ZT_DIAL_OP_REPLACE;
2889                                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
2890                                         p->echobreak = 0;
2891                                 } else {
2892                                         p->dialing = 0;
2893                                         if (p->sig == SIG_E911) {
2894                                                 /* if thru with dialing after offhook */
2895                                                 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
2896                                                         ast_setstate(ast, AST_STATE_UP);
2897                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2898                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2899                                                         break;
2900                                                 } else { /* if to state wait for offhook to dial rest */
2901                                                         /* we now wait for off hook */
2902                                                         ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
2903                                                 }
2904                                         }
2905                                         if (ast->_state == AST_STATE_DIALING) {
2906                                                 if (p->callprogress && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
2907                                                         ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
2908                                                 } 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)))) {
2909                                                         ast_setstate(ast, AST_STATE_RINGING);
2910                                                 } else {
2911                                                         ast_setstate(ast, AST_STATE_UP);
2912                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
2913                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
2914                                                 }
2915                                         }
2916                                 }
2917                         }
2918                         break;
2919                 case ZT_EVENT_ALARM:
2920 #ifdef ZAPATA_PRI
2921 #ifdef PRI_DESTROYCALL
2922                         if (p->call) {
2923                                 if (p->pri && p->pri->pri) {
2924                                         pri_hangup(p->pri->pri, p->call, -1);
2925                                         pri_destroycall(p->pri->pri, p->call);
2926                                 } else
2927                                         ast_log(LOG_WARNING, "The PRI Call have not been destroyed\n");
2928                         }
2929                         if (p->owner)
2930                                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
2931                         p->call = NULL;
2932 #else
2933 #error Please "cvs update" and recompile libpri
2934 #endif
2935 #endif
2936                         p->inalarm = 1;
2937                         res = get_alarms(p);
2938                         ast_log(LOG_WARNING, "Detected alarm on channel %d: %s\n", p->channel, alarm2str(res));
2939                         manager_event(EVENT_FLAG_SYSTEM, "Alarm",
2940                                                                 "Alarm: %s\r\n"
2941                                                                 "Channel: %d\r\n",
2942                                                                 alarm2str(res), p->channel);
2943                         /* fall through intentionally */
2944                 case ZT_EVENT_ONHOOK:
2945                         if (p->radio)
2946                         {
2947                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
2948                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_UNKEY;
2949                                 break;
2950                         }
2951                         switch(p->sig) {
2952                         case SIG_FXOLS:
2953                         case SIG_FXOGS:
2954                         case SIG_FXOKS:
2955                                 p->onhooktime = time(NULL);
2956                                 p->msgstate = -1;
2957                                 /* Check for some special conditions regarding call waiting */
2958                                 if (index == SUB_REAL) {
2959                                         /* The normal line was hung up */
2960                                         if (p->subs[SUB_CALLWAIT].owner) {
2961                                                 /* There's a call waiting call, so ring the phone, but make it unowned in the mean time */
2962                                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2963                                                 if (option_verbose > 2) 
2964                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d still has (callwait) call, ringing phone\n", p->channel);
2965                                                 unalloc_sub(p, SUB_CALLWAIT);   
2966 #if 0
2967                                                 p->subs[index].needanswer = 0;
2968                                                 p->subs[index].needringing = 0;
2969 #endif                                          
2970                                                 p->callwaitingrepeat = 0;
2971                                                 p->cidcwexpire = 0;
2972                                                 p->owner = NULL;
2973                                                 zt_ring_phone(p);
2974                                         } else if (p->subs[SUB_THREEWAY].owner) {
2975                                                 struct timeval tv;
2976                                                 unsigned int mssinceflash;
2977                                                 gettimeofday(&tv, NULL);
2978                                                 mssinceflash = (tv.tv_sec - p->flashtime.tv_sec) * 1000 + (tv.tv_usec - p->flashtime.tv_usec) / 1000;
2979                                                 ast_log(LOG_DEBUG, "Last flash was %d ms ago\n", mssinceflash);
2980                                                 if (mssinceflash < MIN_MS_SINCE_FLASH) {
2981                                                         /* It hasn't been long enough since the last flashook.  This is probably a bounce on 
2982                                                            hanging up.  Hangup both channels now */
2983                                                         if (p->subs[SUB_THREEWAY].owner)
2984                                                                 ast_queue_hangup(p->subs[SUB_THREEWAY].owner);
2985                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2986                                                         ast_log(LOG_DEBUG, "Looks like a bounced flash, hanging up both calls on %d\n", p->channel);
2987                                                 } else if ((ast->pbx) ||
2988                                                         (ast->_state == AST_STATE_UP)) {
2989                                                         if (p->transfer) {
2990                                                                 /* In any case this isn't a threeway call anymore */
2991                                                                 p->subs[SUB_REAL].inthreeway = 0;
2992                                                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2993                                                                 if ((res = attempt_transfer(p)) < 0)
2994                                                                         p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
2995                                                                 else if (res) {
2996                                                                         /* Don't actually hang up at this point */
2997                                                                         break;
2998                                                                 }
2999                                                         } else
3000                                                                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3001                                                 } else {
3002                                                         /* Swap subs and dis-own channel */
3003                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3004                                                         p->owner = NULL;
3005                                                         /* Ring the phone */
3006                                                         zt_ring_phone(p);
3007                                                 }
3008                                         }
3009                                 } else {
3010                                         ast_log(LOG_WARNING, "Got a hangup and my index is %d?\n", index);
3011                                 }
3012                                 /* Fall through */
3013                         default:
3014                                 zt_disable_ec(p);
3015                                 return NULL;
3016                         }
3017                         break;
3018                 case ZT_EVENT_RINGOFFHOOK:
3019                         if (p->inalarm) break;
3020                         if (p->radio)
3021                         {
3022                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3023                                 p->subs[index].f.subclass = AST_CONTROL_RADIO_KEY;
3024                                 break;
3025                         }
3026                         /* for E911, its supposed to wait for offhook then dial
3027                            the second half of the dial string */
3028                         if ((p->sig == SIG_E911) && (ast->_state == AST_STATE_DIALING_OFFHOOK)) {
3029                                 c = strchr(p->dialdest, '/');
3030                                 if (c)
3031                                         c++;
3032                                 else
3033                                         c = p->dialdest;
3034                                 if (*c) snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*0%s#", c);
3035                                 else strcpy(p->dop.dialstr,"M*2#");
3036                                 if (strlen(p->dop.dialstr) > 4) {
3037                                         strcpy(p->echorest, "w");
3038                                         strcpy(p->echorest + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
3039                                         p->echobreak = 1;
3040                                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
3041                                 } else
3042                                         p->echobreak = 0;
3043                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
3044                                         x = ZT_ONHOOK;
3045                                         ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3046                                         ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
3047                                         return NULL;
3048                                         }
3049                                 p->dialing = 1;
3050                                 return &p->subs[index].f;
3051                         }
3052                         switch(p->sig) {
3053                         case SIG_FXOLS:
3054                         case SIG_FXOGS:
3055                         case SIG_FXOKS:
3056                                 switch(ast->_state) {
3057                                 case AST_STATE_RINGING:
3058                                         zt_enable_ec(p);
3059                                         zt_train_ec(p);
3060                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3061                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3062                                         /* Make sure it stops ringing */
3063                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3064                                         ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
3065                                         if (p->cidspill) {
3066                                                 /* Cancel any running CallerID spill */
3067                                                 free(p->cidspill);
3068                                                 p->cidspill = NULL;
3069                                         }
3070                                         p->dialing = 0;
3071                                         p->callwaitcas = 0;
3072                                         if (p->confirmanswer) {
3073                                                 /* Ignore answer if "confirm answer" is enabled */
3074                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
3075                                                 p->subs[index].f.subclass = 0;
3076                                         } else if (!ast_strlen_zero(p->dop.dialstr)) {
3077                                                 /* nick@dccinc.com 4/3/03 - fxo should be able to do deferred dialing */
3078                                                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3079                                                 if (res < 0) {
3080                                                   ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
3081                                                   p->dop.dialstr[0] = '\0';
3082                                                   return NULL;
3083                                                 } else {
3084                                                   ast_log(LOG_DEBUG, "Sent FXO deferred digit string: %s\n", p->dop.dialstr);
3085                                                   p->subs[index].f.frametype = AST_FRAME_NULL;
3086                                                   p->subs[index].f.subclass = 0;
3087                                                   p->dialing = 1;
3088                                                 }
3089                                                 p->dop.dialstr[0] = '\0';
3090                                            ast_setstate(ast, AST_STATE_DIALING);
3091                                         } else
3092                                            ast_setstate(ast, AST_STATE_UP);
3093                                         return &p->subs[index].f;
3094                                 case AST_STATE_DOWN:
3095                                         ast_setstate(ast, AST_STATE_RING);
3096                                         ast->rings = 1;
3097                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3098                                         p->subs[index].f.subclass = AST_CONTROL_OFFHOOK;
3099                                         ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
3100                                         return &p->subs[index].f;
3101                                 case AST_STATE_UP:
3102                                         /* Make sure it stops ringing */
3103                                         zt_set_hook(p->subs[index].zfd, ZT_OFFHOOK);
3104                                         /* Okay -- probably call waiting*/
3105                                         if (p->owner->bridge)
3106                                                         ast_moh_stop(p->owner->bridge);
3107                                         break;
3108                                 default:
3109                                         ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
3110                                 }
3111                                 break;
3112                         case SIG_FXSLS:
3113                         case SIG_FXSGS:
3114                         case SIG_FXSKS:
3115                                 if (ast->_state == AST_STATE_RING) {
3116                                         p->ringt = RINGT;
3117                                 }
3118                                 /* Fall through */
3119                         case SIG_EM:
3120                         case SIG_EM_E1:
3121                         case SIG_EMWINK:
3122                         case SIG_FEATD:
3123                         case SIG_FEATDMF:
3124                         case SIG_E911:
3125                         case SIG_FEATB:
3126                         case SIG_SF:
3127                         case SIG_SFWINK:
3128                         case SIG_SF_FEATD:
3129                         case SIG_SF_FEATDMF:
3130                         case SIG_SF_FEATB:
3131                                 if ((ast->_state == AST_STATE_DOWN) || (ast->_state == AST_STATE_RING)) {
3132                                         if (option_debug)
3133                                                 ast_log(LOG_DEBUG, "Ring detected\n");
3134                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3135                                         p->subs[index].f.subclass = AST_CONTROL_RING;
3136                                 } else if (p->outgoing && ((ast->_state == AST_STATE_RINGING) || (ast->_state == AST_STATE_DIALING))) {
3137                                         if (option_debug)
3138                                                 ast_log(LOG_DEBUG, "Line answered\n");
3139                                         if (p->confirmanswer) {
3140                                                 p->subs[index].f.frametype = AST_FRAME_NULL;
3141                                                 p->subs[index].f.subclass = 0;
3142                                         } else {
3143                                                 p->subs[index].f.frametype = AST_FRAME_CONTROL;
3144                                                 p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3145                                                 ast_setstate(ast, AST_STATE_UP);
3146                                         }
3147                                 } else if (ast->_state != AST_STATE_RING)
3148                                         ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
3149                                 break;
3150                         default:
3151                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
3152                         }
3153                         break;
3154                 case ZT_EVENT_RINGEROFF:
3155                         if (p->inalarm) break;
3156                         if (p->radio) break;
3157                         ast->rings++;
3158                         if ((ast->rings > p->cidrings) && (p->cidspill)) {
3159                                 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
3160                                 free(p->cidspill);
3161                                 p->cidspill = NULL;
3162                                 p->callwaitcas = 0;
3163                         }
3164                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3165                         p->subs[index].f.subclass = AST_CONTROL_RINGING;
3166                         break;
3167                 case ZT_EVENT_RINGERON:
3168                         break;
3169                 case ZT_EVENT_NOALARM:
3170                         p->inalarm = 0;
3171                         ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
3172                         manager_event(EVENT_FLAG_SYSTEM, "AlarmClear",
3173                                                                 "Channel: %d\r\n", p->channel);
3174                         break;
3175                 case ZT_EVENT_WINKFLASH:
3176                         if (p->inalarm) break;
3177                         if (p->radio) break;
3178                         /* Remember last time we got a flash-hook */
3179                         gettimeofday(&p->flashtime, NULL);
3180                         switch(p->sig) {
3181                         case SIG_FXOLS:
3182                         case SIG_FXOGS:
3183                         case SIG_FXOKS:
3184                                 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
3185                                         index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
3186                                 p->callwaitcas = 0;
3187                                 if (index == SUB_REAL) {
3188                                         if (p->subs[SUB_CALLWAIT].owner) {
3189                                                 /* Swap to call-wait */
3190                                                 swap_subs(p, SUB_REAL, SUB_CALLWAIT);
3191                                                 tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
3192                                                 p->owner = p->subs[SUB_REAL].owner;
3193                                                 ast_log(LOG_DEBUG, "Making %s the new owner\n", p->owner->name);
3194                                                 if (p->owner->_state == AST_STATE_RINGING) {
3195                                                         ast_setstate(p->owner, AST_STATE_UP);
3196                                                         p->subs[SUB_REAL].needanswer = 1;
3197                                                 }
3198                                                 p->callwaitingrepeat = 0;
3199                                                 p->cidcwexpire = 0;
3200                                                 /* Start music on hold if appropriate */
3201                                                 if (!p->subs[SUB_CALLWAIT].inthreeway && p->subs[SUB_CALLWAIT].owner->bridge)
3202                                                                 ast_moh_start(p->subs[SUB_CALLWAIT].owner->bridge, NULL);
3203                                                 if (p->subs[SUB_REAL].owner->bridge)
3204                                                                 ast_moh_stop(p->subs[SUB_REAL].owner->bridge);
3205                                         } else if (!p->subs[SUB_THREEWAY].owner) {
3206                                                 char callerid[256];
3207                                                 if (p->threewaycalling && !check_for_conference(p)) {
3208                                                         if (p->zaptrcallerid && p->owner && p->owner->callerid)
3209                                                                 strncpy(callerid, p->owner->callerid, sizeof(callerid) - 1);
3210                                                         /* XXX This section needs much more error checking!!! XXX */
3211                                                         /* Start a 3-way call if feasible */
3212                                                         if ((ast->pbx) ||
3213                                                                         (ast->_state == AST_STATE_UP) ||
3214                                                                         (ast->_state == AST_STATE_RING)) {
3215                                                                 if (!alloc_sub(p, SUB_THREEWAY)) {
3216                                                                         /* Make new channel */
3217                                                                         chan = zt_new(p, AST_STATE_RESERVED, 0, SUB_THREEWAY, 0, 0);
3218                                                                         if (p->zaptrcallerid) {
3219                                                                                 if (!p->origcallerid) {
3220                                                                                         p->origcallerid = malloc(strlen(p->callerid) + 1);
3221                                                                                         strncpy(p->origcallerid, p->callerid, strlen(p->callerid) + 1);
3222                                                                                 }
3223                                                                                 strncpy(p->callerid, callerid, sizeof(p->callerid) -1);
3224                                                                         }
3225                                                                         /* Swap things around between the three-way and real call */
3226                                                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3227                                                                         /* Disable echo canceller for better dialing */
3228                                                                         zt_disable_ec(p);
3229                                                                         res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_DIALRECALL);
3230                                                                         if (res)
3231                                                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
3232                                                                         p->owner = chan;
3233                                                                         if (chan && pthread_create(&threadid, &attr, ss_thread, chan)) {
3234                                                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
3235                                                                                 res = tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
3236                                              &n